<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title th:text="'智能学习引擎 - ' + ${point.title}">智能学习引擎</title>
  <style>
    /* 重置和基础样式 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    :root {
      --primary-color: #667eea;
      --secondary-color: #764ba2;
      --success-color: #4CAF50;
      --info-color: #2196F3;
      --warning-color: #FF9800;
      --danger-color: #f44336;
      --light-bg: #f8f9fa;
      --dark-text: #333;
      --medium-text: #666;
      --light-text: #999;
      --border-color: #e9ecef;
    }

    body {
      background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
      color: var(--dark-text);
      min-height: 100vh;
      padding: 0;
    }

    .app-container {
      max-width: 100%;
      margin: 0 auto;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }

    /* 导航栏 */
    .navbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: rgba(255, 255, 255, 0.98);
      padding: 12px 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      position: sticky;
      top: 0;
      z-index: 100;
    }

    .nav-brand {
      font-size: 20px;
      font-weight: bold;
      color: var(--secondary-color);
      display: flex;
      align-items: center;
    }

    .nav-buttons {
      display: flex;
      gap: 10px;
    }

    .btn {
      padding: 8px 16px;
      border-radius: 6px;
      text-decoration: none;
      font-weight: 600;
      font-size: 14px;
      transition: all 0.3s;
      display: inline-flex;
      align-items: center;
    }

    .btn-outline {
      border: 2px solid var(--secondary-color);
      color: var(--secondary-color);
      background: transparent;
    }

    .btn-outline:hover {
      background: var(--secondary-color);
      color: white;
    }

    /* 主内容区域 */
    .main-content {
      flex: 1;
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
      width: 100%;
    }

    /* 学习卡片 */
    .learning-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      margin-bottom: 20px;
    }

    .card-header {
      padding: 20px;
      background: linear-gradient(135deg, #f8f9fa, #e9ecef);
      border-bottom: 1px solid var(--border-color);
    }

    .card-title {
      font-size: 24px;
      color: var(--dark-text);
      margin-bottom: 8px;
    }

    .card-subtitle {
      color: var(--medium-text);
      font-size: 14px;
      line-height: 1.5;
    }

    .card-body {
      padding: 25px;
    }

    /* 进度条 */
    .duolingo-progress {
      margin: 20px 0;
      padding: 15px;
      background: var(--light-bg);
      border-radius: 10px;
    }

    .progress-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .progress-label {
      font-weight: 600;
      color: var(--dark-text);
    }

    .progress-percentage {
      color: var(--info-color);
      font-weight: bold;
    }

    .progress-bar-container {
      height: 12px;
      background: var(--border-color);
      border-radius: 6px;
      overflow: hidden;
    }

    .progress-bar {
      height: 100%;
      background: linear-gradient(90deg, var(--info-color), var(--primary-color));
      border-radius: 6px;
      transition: width 0.5s ease;
      width: 0%;
    }

    /* 智能路径指示器 */
    .path-indicator {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 25px;
      padding: 15px;
      background: var(--light-bg);
      border-radius: 10px;
      border-left: 4px solid var(--info-color);
    }

    .path-info h3 {
      color: var(--dark-text);
      margin-bottom: 5px;
      font-size: 18px;
    }

    .path-info p {
      color: var(--medium-text);
      font-size: 14px;
      margin: 0;
    }

    .path-tag {
      background: var(--info-color);
      color: white;
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: bold;
    }

    /* 阶段容器 */
    .stages-container {
      display: grid;
      gap: 20px;
      margin-bottom: 25px;
    }

    .stage-card {
      background: white;
      border: 2px solid var(--border-color);
      border-radius: 10px;
      padding: 20px;
      transition: all 0.3s;
      cursor: pointer;
      position: relative;
    }

    .stage-card.current {
      border-color: var(--info-color);
      background: #f0f8ff;
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(33, 150, 243, 0.15);
    }

    .stage-card.completed {
      border-color: var(--success-color);
      background: #f8fff8;
    }

    .stage-card.locked {
      opacity: 0.6;
      cursor: not-allowed;
    }

    .stage-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
    }

    .stage-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 18px;
      flex-shrink: 0;
    }

    .stage-card.current .stage-icon {
      background: var(--info-color);
      color: white;
    }

    .stage-card.completed .stage-icon {
      background: var(--success-color);
      color: white;
    }

    .stage-card.locked .stage-icon {
      background: #6c757d;
      color: white;
    }

    .stage-info {
      flex: 1;
    }

    .stage-name {
      font-weight: 600;
      color: var(--dark-text);
      margin-bottom: 4px;
    }

    .stage-desc {
      font-size: 13px;
      color: var(--medium-text);
      line-height: 1.4;
    }

    .stage-status {
      text-align: right;
      font-size: 12px;
      color: var(--medium-text);
    }

    .stage-duration {
      display: block;
      margin-bottom: 4px;
    }

    /* 学习内容区域 */
    .learning-content {
      min-height: 400px;
      background: white;
      border-radius: 10px;
      padding: 25px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      margin-bottom: 20px;
    }

    /* 概念理解样式 */
    .concept-content {
      line-height: 1.7;
    }

    .concept-analogy {
      background: #fff3cd;
      border-left: 4px solid var(--warning-color);
      padding: 15px;
      margin: 20px 0;
      border-radius: 0 8px 8px 0;
    }

    .concept-visual {
      background: #e7f3ff;
      padding: 20px;
      border-radius: 8px;
      margin: 20px 0;
      text-align: center;
    }

    .visual-diagram {
      font-family: 'Courier New', monospace;
      background: white;
      padding: 15px;
      border-radius: 6px;
      margin: 15px 0;
      border: 1px solid var(--border-color);
    }

    /* 测验题目样式 */
    .quiz-container {
      margin: 20px 0;
    }

    .quiz-question {
      margin-bottom: 20px;
      padding: 20px;
      background: white;
      border: 1px solid var(--border-color);
      border-radius: 10px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }

    .question-text {
      font-weight: 600;
      margin-bottom: 15px;
      font-size: 16px;
      line-height: 1.5;
    }

    .options-container {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .option {
      padding: 12px 15px;
      border: 2px solid var(--border-color);
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
    }

    .option:hover {
      border-color: var(--info-color);
      background: var(--light-bg);
    }

    .option.selected {
      border-color: var(--info-color);
      background: #e7f3ff;
    }

    .code-exercise {
      margin: 20px 0;
    }

    .code-prompt {
      background: var(--light-bg);
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      border-left: 4px solid var(--info-color);
    }

    /* 桌面端代码编辑器 */
    .desktop-code-editor {
      display: none;
    }

    /* 移动端代码构建器 */
    .mobile-code-builder {
      display: none;
    }

    .code-blocks {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin: 15px 0;
    }

    .code-block {
      background: white;
      border: 2px solid var(--border-color);
      padding: 12px 15px;
      border-radius: 8px;
      cursor: grab;
      font-family: 'Courier New', monospace;
      font-size: 14px;
      transition: all 0.2s;
      user-select: none;
    }

    .code-block:hover {
      border-color: var(--info-color);
      transform: translateY(-2px);
    }

    .code-workspace {
      background: #2d2d2d;
      color: #f8f8f2;
      padding: 20px;
      border-radius: 8px;
      min-height: 200px;
      font-family: 'Courier New', monospace;
      margin: 15px 0;
      position: relative;
    }

    .code-line {
      margin-bottom: 8px;
      display: flex;
      align-items: center;
    }

    .line-number {
      color: #6a9955;
      margin-right: 15px;
      min-width: 20px;
    }

    .code-slot {
      display: inline-block;
      min-width: 100px;
      height: 24px;
      border-bottom: 2px dashed #4CAF50;
      margin: 0 5px;
      vertical-align: middle;
    }

    .code-slot.filled {
      border-bottom: none;
      background: #4CAF50;
      color: white;
      padding: 2px 8px;
      border-radius: 4px;
    }

    /* 控制按钮 */
    .action-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid var(--border-color);
    }

    .action-btn {
      padding: 12px 25px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-weight: 600;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn-prev {
      background: #6c757d;
      color: white;
    }

    .btn-next {
      background: var(--success-color);
      color: white;
    }

    .btn-prev:disabled {
      background: #ccc;
      cursor: not-allowed;
    }

    /* ========== 优化：学习笔记和问题记录样式 ========== */
    .learning-notes-container {
      margin-top: 30px;
      border-top: 1px solid var(--border-color);
      padding-top: 20px;
    }

    .notes-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
    }

    .notes-title {
      font-size: 18px;
      font-weight: 600;
      color: var(--dark-text);
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .notes-toggle {
      background: none;
      border: none;
      color: var(--info-color);
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .notes-toggle:hover {
      text-decoration: underline;
    }

    .notes-form {
      background: var(--light-bg);
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
    }

    .note-type-selector {
      display: flex;
      gap: 10px;
      margin-bottom: 10px;
    }

    .note-type-btn {
      padding: 6px 12px;
      border: 1px solid #ddd;
      border-radius: 20px;
      background: white;
      cursor: pointer;
      font-size: 12px;
      transition: all 0.2s;
    }

    .note-type-btn.active {
      background: var(--info-color);
      color: white;
      border-color: var(--info-color);
    }

    .note-type-btn.question {
      border-color: var(--warning-color);
    }

    .note-type-btn.question.active {
      background: var(--warning-color);
    }

    .note-type-btn.insight {
      border-color: var(--success-color);
    }

    .note-type-btn.insight.active {
      background: var(--success-color);
    }

    .notes-form textarea {
      width: 100%;
      min-height: 80px;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      resize: vertical;
      font-family: inherit;
    }

    .answer-input {
      margin-top: 10px;
      display: none;
    }

    .answer-input textarea {
      min-height: 60px;
    }

    .notes-actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 10px;
    }

    .notes-list {
      max-height: 400px;
      overflow-y: auto;
    }

    .note-item {
      background: white;
      border: 1px solid var(--border-color);
      border-radius: 6px;
      padding: 12px 15px;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }

    .note-item.question {
      border-left: 4px solid var(--warning-color);
    }

    .note-item.insight {
      border-left: 4px solid var(--success-color);
    }

    .note-item.resolved {
      opacity: 0.8;
      background: #f8fff8;
    }

    .note-content {
      flex: 1;
    }

    .note-type-badge {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 10px;
      font-size: 10px;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .note-type-badge.question {
      background: #fff3cd;
      color: #856404;
    }

    .note-type-badge.insight {
      background: #d1ecf1;
      color: #0c5460;
    }

    .note-text {
      margin-bottom: 8px;
      line-height: 1.5;
    }

    .note-answer {
      background: var(--light-bg);
      padding: 8px 10px;
      border-radius: 4px;
      margin-top: 8px;
      border-left: 2px solid var(--info-color);
    }

    .note-answer-label {
      font-size: 12px;
      color: #6c757d;
      margin-bottom: 4px;
    }

    .note-meta {
      font-size: 12px;
      color: #6c757d;
    }

    .note-actions {
      display: flex;
      gap: 8px;
    }

    .note-action {
      background: none;
      border: none;
      cursor: pointer;
      font-size: 14px;
      padding: 4px;
      border-radius: 3px;
    }

    .note-action.resolve {
      color: var(--success-color);
    }

    .note-action.resolve:hover {
      background: rgba(76, 175, 80, 0.1);
    }

    .note-action.edit {
      color: var(--info-color);
    }

    .note-action.edit:hover {
      background: rgba(33, 150, 243, 0.1);
    }

    .note-action.delete {
      color: var(--danger-color);
    }

    .note-action.delete:hover {
      background: rgba(244, 67, 54, 0.1);
    }

    .notes-progress {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-top: 15px;
      padding: 10px;
      background: #e7f3ff;
      border-radius: 6px;
      font-size: 14px;
    }

    .notes-progress.warning {
      background: #fff3cd;
      color: #856404;
    }

    .notes-progress i {
      font-size: 16px;
    }

    /* 代码编辑器样式 */
    .code-answer {
      font-family: 'Courier New', monospace;
      background: var(--light-bg);
      border: 1px solid #ddd;
    }

    .code-answer:focus {
      outline: none;
      border-color: var(--info-color);
      box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
    }

    /* 文本答案样式 */
    .text-answer {
      resize: vertical;
      min-height: 100px;
    }

    .text-answer:focus {
      outline: none;
      border-color: var(--info-color);
      box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
    }

    /* 填空题样式 */
    .blank-answer {
      transition: all 0.2s;
    }

    .blank-answer:focus {
      outline: none;
      border-color: var(--info-color);
      box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
    }

    /* 解析提示样式 */
    .question-explanation {
      border-left: 4px solid var(--warning-color);
      background: #fff3cd;
      color: #856404;
    }

    /* 题目头部样式 */
    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .question-number {
      font-weight: bold;
      color: var(--dark-text);
    }

    .question-type-badge {
      background: var(--info-color);
      color: white;
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: bold;
    }

    /* 选项样式优化 */
    .option {
      padding: 12px 15px;
      border: 2px solid var(--border-color);
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      margin-bottom: 8px;
    }

    .option:hover {
      border-color: var(--info-color);
      background: var(--light-bg);
      transform: translateY(-1px);
    }

    .option.selected {
      border-color: var(--info-color);
      background: #e7f3ff;
      box-shadow: 0 2px 5px rgba(33, 150, 243, 0.2);
    }

    /* 输入框焦点样式 */
    .blank-answer:focus,
    .text-answer:focus {
      outline: none;
      border-color: var(--info-color);
      box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
    }

    /* ========== 新增：测验导航和标记样式 ========== */
    .quiz-navigation {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20px 0;
      padding: 15px;
      background: var(--light-bg);
      border-radius: 8px;
    }

    .quiz-progress {
      font-size: 14px;
      color: var(--medium-text);
    }

    .quiz-controls {
      display: flex;
      gap: 10px;
    }

    .mark-btn {
      background: #ffc107;
      color: #856404;
      border: none;
      padding: 8px 15px;
      border-radius: 20px;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .mark-btn.marked {
      background: #ff9800;
      color: white;
    }

    .explanation-btn {
      background: #17a2b8;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 20px;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .question-explanation {
      display: none;
      margin-top: 15px;
      padding: 15px;
      background: #e7f3ff;
      border-radius: 8px;
      border-left: 4px solid #2196F3;
    }

    .question-explanation.show {
      display: block;
    }

    .quiz-complete-btn {
      background: var(--success-color);
      color: white;
      border: none;
      padding: 12px 25px;
      border-radius: 8px;
      cursor: pointer;
      font-weight: 600;
      font-size: 16px;
    }

    .quiz-complete-btn:disabled {
      background: #ccc;
      cursor: not-allowed;
    }

    /* 题目状态指示器 */
    .question-status-indicator {
      display: flex;
      gap: 5px;
      margin: 15px 0;
      flex-wrap: wrap;
    }

    .status-dot {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: var(--border-color);
      cursor: pointer;
    }

    .status-dot.answered {
      background: var(--success-color);
    }

    .status-dot.current {
      border: 2px solid var(--info-color);
      background: white;
    }

    .status-dot.marked {
      background: #ffc107;
    }

    /* 移动端优化 */
    @media (max-width: 768px) {
      .main-content {
        padding: 15px;
      }

      .navbar {
        padding: 10px 15px;
      }

      .nav-buttons {
        flex-direction: column;
        gap: 8px;
      }

      .btn {
        padding: 6px 12px;
        font-size: 12px;
      }

      .card-body {
        padding: 20px 15px;
      }

      .path-indicator {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }

      .path-tag {
        align-self: flex-start;
      }

      .stage-header {
        flex-direction: column;
        align-items: flex-start;
      }

      .stage-icon {
        margin-right: 0;
        margin-bottom: 10px;
      }

      .stage-status {
        align-self: flex-start;
        margin-top: 10px;
      }

      .action-buttons {
        flex-direction: column;
        gap: 10px;
      }

      .action-btn {
        width: 100%;
        justify-content: center;
      }

      /* 移动端显示代码构建器 */
      .mobile-code-builder {
        display: block;
      }

      /* 移动端笔记优化 */
      .note-item {
        flex-direction: column;
      }

      .note-actions {
        align-self: flex-end;
        margin-top: 8px;
      }

      .note-type-selector {
        flex-wrap: wrap;
      }

      /* 移动端测验导航优化 */
      .quiz-navigation {
        flex-direction: column;
        gap: 15px;
      }

      .quiz-controls {
        flex-wrap: wrap;
        justify-content: center;
      }
    }

    /* 桌面端优化 */
    @media (min-width: 769px) {
      .desktop-code-editor {
        display: block;
      }

      .stages-container {
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      }

      .main-content {
        padding: 30px;
      }
    }

    /* 大屏幕优化 */
    @media (min-width: 1200px) {
      .main-content {
        padding: 40px;
      }
    }
    .loading-text {
      text-align: center;
      padding: 40px 20px;
      color: var(--light-text);
      font-size: 14px;
    }

    .loading-text i {
      margin-right: 8px;
    }

    .error-text {
      text-align: center;
      padding: 40px 20px;
      color: var(--danger-color);
    }

    .no-points {
      text-align: center;
      padding: 40px 20px;
      color: var(--light-text);
    }

    .btn-purple {
      background: linear-gradient(135deg, #6f42c1, #8e24aa);
      color: white;
      border: none;
      box-shadow: 0 4px 15px rgba(111, 66, 193, 0.3);
    }

    .btn-cyan {
      background: linear-gradient(135deg, #17a2b8, #20c997);
      color: white;
      border: none;
      box-shadow: 0 4px 15px rgba(23, 162, 184, 0.3);
    }
  </style>
</head>
<body>
<div class="app-container">
  <!-- 导航栏 -->
  <nav class="navbar">
    <div class="nav-brand">
      <span style="margin-right: 8px;">🚀</span> 渐进学习平台
    </div>
    <div class="nav-buttons">
      <a th:href="@{/knowledge/gym}" class="btn btn-outline">返回训练馆</a>
      <a th:href="@{/practice/choice(pointId=${point.id})}" class="btn btn-outline" style="background: var(--primary-color); color: white;">
        🎯 练习模式
      </a>
      <a th:href="@{/}" class="btn btn-outline">返回首页</a>
    </div>
  </nav>

  <!-- 主内容区域 -->
  <div class="main-content">
    <!-- 学习卡片 -->
    <div class="learning-card">
      <div class="card-header">
        <h1 class="card-title" id="contentTitle" th:text="${point.title}">知识点标题</h1>
        <p class="card-subtitle" id="contentDescription" th:text="${point.description}">知识点描述</p>

        <!-- 多邻国风格进度条 -->
        <div class="duolingo-progress">
          <div class="progress-header">
            <span class="progress-label">学习进度</span>
            <span class="progress-percentage" id="progressPercentage">0%</span>
          </div>
          <div class="progress-bar-container">
            <div class="progress-bar" id="progressBar"></div>
          </div>
        </div>
      </div>

      <div class="card-body">
        <!-- 智能路径指示器 -->
        <div class="path-indicator">
          <div class="path-info">
            <h3>🎯 智能学习路径</h3>
            <p>系统已为你推荐最适合这个知识点的学习阶段</p>
          </div>
          <div class="path-tag" id="pathTypeTag" th:text="${point.knowledgeType}">概念理解型</div>
        </div>

        <!-- 阶段容器 -->
        <div class="stages-container" id="stagesContainer">
          <!-- 阶段会通过JavaScript动态生成 -->
        </div>

        <!-- 学习内容区域 -->
        <div class="learning-content" id="learningContent">
          <div class="loading-state">
            <div style="text-align: center; padding: 40px; color: #666;">
              <div style="font-size: 48px; margin-bottom: 20px;">📚</div>
              <p>选择学习阶段开始</p>
            </div>
          </div>
        </div>

        <!-- ========== 优化：学习笔记和问题记录区域 ========== -->
        <div class="learning-notes-container" id="learningNotesContainer" style="display: none;">
          <div class="notes-header">
            <h3 class="notes-title">
              <span>📝</span> 学习笔记与问题记录
            </h3>
            <button class="notes-toggle" id="notesToggle" onclick="toggleNotes()">
              <span>收起</span>
              <span>▲</span>
            </button>
          </div>

          <div class="notes-form" id="notesForm">
            <div class="note-type-selector">
              <button class="note-type-btn question active" data-type="question" onclick="selectNoteType('question')">
                ❓ 记录问题
              </button>
              <button class="note-type-btn insight" data-type="insight" onclick="selectNoteType('insight')">
                💡 记录心得
              </button>
            </div>

            <textarea id="noteInput" placeholder="记录你的思考、疑问或心得..."></textarea>

            <div class="answer-input" id="answerInput">
              <div class="answer-label">💬 问题解答：</div>
              <textarea id="answerText" placeholder="自己试着去寻找解决问题的办法会让你进步更快哦！"></textarea>
            </div>

            <div class="notes-actions">
              <button class="action-btn" onclick="clearNote()" style="background: #6c757d; padding: 8px 15px;">
                清空
              </button>
              <button class="action-btn" onclick="addNote()" style="background: var(--info-color); padding: 8px 15px;">
                添加记录
              </button>
            </div>
          </div>

          <div class="notes-list" id="notesList">
            <!-- 笔记列表将通过JavaScript动态生成 -->
          </div>

          <div class="notes-progress" id="notesProgress">
            <i>📋</i>
            <span id="notesProgressText">已记录 0 个问题，0 个待处理</span>
          </div>
        </div>

        <!-- 控制按钮 -->
        <div class="action-buttons">
          <button class="action-btn btn-prev" onclick="previousStage()" disabled id="prevBtn">
            ← 上一阶段
          </button>
          <button class="action-btn btn-next" onclick="nextStage()" id="nextBtn">
            下一阶段 →
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  // 知识点类型和学习路径配置
  const knowledgeConfigs = {
    // 概念理解型知识点（如IoC、设计模式等）
    "概念理解型": {
      name: "概念理解型",
      stages: [
        {
          id: 1,
          type: "concept",
          name: "核心概念解析",
          icon: "💡",
          description: "通过类比和生活化语言理解抽象概念",
          duration: "8-12分钟",
          required: true
        },
        {
          id: 2,
          type: "analogy",
          name: "生活化类比",
          icon: "🔍",
          description: "用熟悉的场景理解复杂概念",
          duration: "6-10分钟",
          required: true
        },
        {
          id: 3,
          type: "example",
          name: "实际示例",
          icon: "📚",
          description: "通过实际案例加深理解",
          duration: "8-15分钟",
          required: true
        },
        {
          id: 4,
          type: "quiz",
          name: "随堂练习",
          icon: "🎯",
          description: "通过练习检验学习效果",
          duration: "5-10分钟",
          required: true
        }
      ]
    },

    // API学习型知识点（如集合类、工具类等）
    "API学习型": {
      name: "API学习型",
      stages: [
        {
          id: 1,
          type: "overview",
          name: "API概览",
          icon: "📋",
          description: "了解API的功能和用途",
          duration: "5-8分钟",
          required: true
        },
        {
          id: 2,
          type: "usage",
          name: "使用示例",
          icon: "🔧",
          description: "查看实际使用场景和示例",
          duration: "10-15分钟",
          required: true
        },
        {
          id: 3,
          type: "practice",
          name: "动手练习",
          icon: "💻",
          description: "在代码中实际应用API",
          duration: "12-18分钟",
          required: false
        },
        {
          id: 4,
          type: "quiz",
          name: "应用测验",
          icon: "🎯",
          description: "检验API掌握程度",
          duration: "6-10分钟",
          required: true
        }
      ]
    },

    // 代码实践型知识点（如算法、业务逻辑等）
    "代码实践型": {
      name: "代码实践型",
      stages: [
        {
          id: 1,
          type: "concept",
          name: "思路理解",
          icon: "🧠",
          description: "理解算法思路和实现逻辑",
          duration: "8-12分钟",
          required: true
        },
        {
          id: 2,
          type: "visualization",
          name: "过程可视化",
          icon: "📊",
          description: "通过动画理解执行过程",
          duration: "10-15分钟",
          required: true
        },
        {
          id: 3,
          type: "coding",
          name: "代码实现",
          icon: "💻",
          description: "动手编写和调试代码",
          duration: "15-25分钟",
          required: true
        },
        {
          id: 4,
          type: "quiz",
          name: "应用测验",
          icon: "🎯",
          description: "检验代码掌握程度",
          duration: "8-12分钟",
          required: true
        }
      ]
    }
  };

  // 当前学习状态
  let currentState = {
    knowledgeType: null,
    currentStage: 0,
    completedStages: [],
    currentContent: {
      title: null,
      description: null,
      type: null
    },
    pointId: null,
    // 优化：学习笔记和问题记录
    notes: [], // 存储所有阶段的笔记和问题
    currentNoteType: 'question', // 当前选择的笔记类型
    // 新增：测验状态
    quiz: {
      questions: [],
      currentQuestionIndex: 0,
      answers: {},
      markedQuestions: new Set(),
      showExplanations: {}
    }
  };

  // 全局变量存储从后端获取的学习内容
  let learningContentData = {};

  // 设备检测
  const isMobile = window.innerWidth <= 768;

  // 初始化页面
  document.addEventListener('DOMContentLoaded', function() {
    // 设置知识点类型
    const pathTypeTag = document.getElementById('pathTypeTag');

    // 从Thymeleaf属性获取知识点类型
    currentState.knowledgeType = "[[${point.knowledgeType}]]";

    // 如果从Thymeleaf获取失败，使用默认值
    if (currentState.knowledgeType.includes('${')) {
      currentState.knowledgeType = pathTypeTag ? pathTypeTag.textContent.trim() : "概念理解型";
    }

    // 设置其他属性
    const titleElement = document.getElementById('contentTitle');
    const descriptionElement = document.getElementById('contentDescription');

    currentState.currentContent.title = titleElement ? titleElement.textContent : '未知标题';
    currentState.currentContent.description = descriptionElement ? descriptionElement.textContent : '未知描述';
    currentState.currentContent.type = currentState.knowledgeType;
    currentState.pointId = [[${pointId}]];

    console.log('初始化状态:', currentState);

    // 检查知识点类型是否在配置中
    if (!knowledgeConfigs[currentState.knowledgeType]) {
      console.warn('未找到知识点类型配置:', currentState.knowledgeType);
      // 使用默认配置
      currentState.knowledgeType = "概念理解型";
    }

    renderLearningPath();
    updateContentDisplay();
    updateProgressBar();

    // 设置路径类型标签
    if (pathTypeTag) {
      pathTypeTag.textContent = knowledgeConfigs[currentState.knowledgeType].name;
    }
  });

  // 渲染学习路径
  function renderLearningPath() {
    const container = document.getElementById('stagesContainer');
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    container.innerHTML = '';

    pathConfig.stages.forEach((stage, index) => {
      const stageElement = createStageElement(stage, index);
      container.appendChild(stageElement);
    });
  }

  // 创建阶段元素
  function createStageElement(stage, index) {
    const stageDiv = document.createElement('div');
    let stageClass = 'stage-card';

    if (index < currentState.currentStage) {
      stageClass += ' completed';
    } else if (index === currentState.currentStage) {
      stageClass += ' current';
    } else if (index > currentState.currentStage) {
      stageClass += ' locked';
    }

    stageDiv.className = stageClass;
    stageDiv.onclick = () => selectStage(index);

    stageDiv.innerHTML = `
      <div class="stage-header">
        <div class="stage-icon">${stage.icon}</div>
        <div class="stage-info">
          <div class="stage-name">${stage.name}</div>
          <div class="stage-desc">${stage.description}</div>
        </div>
        <div class="stage-status">
          <span class="stage-duration">${stage.duration}</span>
          ${stage.required ? '<span style="color:#666;">必修</span>' : '<span style="color:#999;">选修</span>'}
        </div>
      </div>
    `;

    return stageDiv;
  }

  // 更新进度条
  function updateProgressBar() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    const progress = ((currentState.currentStage + 1) / pathConfig.stages.length) * 100;

    const progressBar = document.getElementById('progressBar');
    const progressPercentage = document.getElementById('progressPercentage');

    if (progressBar && progressPercentage) {
      progressBar.style.width = progress + '%';
      progressPercentage.textContent = Math.round(progress) + '%';
    }
  }

  // 选择阶段
  function selectStage(stageIndex) {
    try {
      const pathConfig = knowledgeConfigs[currentState.knowledgeType];
      if (!pathConfig || !pathConfig.stages[stageIndex]) {
        console.error('无效的阶段选择');
        return;
      }

      // 只能选择当前阶段或已完成的阶段
      if (stageIndex > currentState.currentStage) {
        return;
      }

      currentState.currentStage = stageIndex;
      renderLearningPath();
      loadStageContent(pathConfig.stages[stageIndex]);
      updateNavigationButtons();
      updateProgressBar();
    } catch (error) {
      console.error('选择阶段时出错:', error);
    }
  }

  // 加载阶段内容
  function loadStageContent(stage) {
    const contentArea = document.getElementById('learningContent');

    // 显示加载状态
    contentArea.innerHTML = `
      <div class="loading-text">
        <div style="font-size: 48px; margin-bottom: 20px;">⏳</div>
        <p>加载学习内容中...</p>
      </div>
    `;

    // 显示学习笔记区域 - 确保在所有阶段类型都显示
    const notesContainer = document.getElementById('learningNotesContainer');
    if (notesContainer) {
      notesContainer.style.display = 'block';
    }

    // 首先加载学习内容，然后根据阶段类型渲染
    loadLearningContent().then(() => {
      switch (stage.type) {
        case 'concept':
          contentArea.innerHTML = renderConceptContent();
          break;
        case 'analogy':
          contentArea.innerHTML = renderAnalogyContent();
          break;
        case 'coding':
          contentArea.innerHTML = isMobile ? renderMobileCodingContent() : renderDesktopCodingContent();
          break;
        case 'quiz':
          contentArea.innerHTML = renderQuizContent();
          // 新增：测验内容渲染后立即加载题目
          setTimeout(() => {
            loadQuizQuestions();
          }, 100);
          break;
        case 'overview':
          contentArea.innerHTML = renderOverviewContent();
          break;
        case 'usage':
          contentArea.innerHTML = renderUsageContent();
          break;
        case 'practice':
          contentArea.innerHTML = renderPracticeContent();
          break;
        case 'visualization':
          contentArea.innerHTML = renderVisualizationContent();
          break;
        case 'example':
          contentArea.innerHTML = renderExampleContent();
          break;
        default:
          contentArea.innerHTML = renderDefaultContent(stage);
      }

      // 渲染当前阶段的笔记
      renderNotes();
    }).catch(error => {
      console.error('加载学习内容失败:', error);
      contentArea.innerHTML = `
        <div class="error-text">
          <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
          <p>加载内容失败，请刷新页面重试</p>
          <button onclick="retryLoadContent()" style="margin-top: 10px; padding: 8px 16px; background: var(--danger-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
            重试加载
          </button>
        </div>
      `;
    });
  }

  // 从后端加载学习内容
  function loadLearningContent() {
    return fetch('/knowledge/training/' + currentState.pointId + '/learning-content')
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(data => {
              learningContentData = data;
              return data;
            });
  }

  // 重试加载内容
  function retryLoadContent() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    loadStageContent(pathConfig.stages[currentState.currentStage]);
  }

  // 渲染概念理解内容 - 使用动态数据
  function renderConceptContent() {
    const conceptData = learningContentData.conceptContent ||
            generateDynamicConcept(currentState.currentContent.title);

    return `
      <div class="concept-content">
        <h3>💡 ${currentState.currentContent.title} 核心概念</h3>
        <p>${currentState.currentContent.description}</p>

        <div class="concept-analogy">
          <h4>🤔 核心思想</h4>
          <p>${conceptData}</p>
        </div>

        <div class="concept-visual">
          <h4>🔄 工作原理</h4>
          <div class="visual-diagram">
            ${getConceptDiagram(currentState.currentContent.title)}
          </div>
        </div>

        <div style="margin-top: 20px;">
          <h4>🎯 关键要点：</h4>
          <ul style="line-height: 1.8;">
            <li><strong>核心作用：</strong>理解其主要功能和用途</li>
            <li><strong>工作方式：</strong>掌握其基本运作原理</li>
            <li><strong>应用场景：</strong>了解适用的场景和限制</li>
            <li><strong>与其他概念的关系：</strong>理解其在技术体系中的位置</li>
          </ul>
        </div>
      </div>
    `;
  }

  // 渲染生活化类比内容 - 使用动态数据
  function renderAnalogyContent() {
    const analogyData = learningContentData.analogyContent ||
            generateDynamicAnalogy(currentState.currentContent.title);

    return `
      <div class="concept-content">
        <h3>🔍 ${currentState.currentContent.title} 生活化类比</h3>

        <div style="display: grid; gap: 20px; margin-top: 20px;">
          <div style="background: #e7f3ff; padding: 20px; border-radius: 10px;">
            <h4>🎯 理解类比</h4>
            <p>${analogyData}</p>
          </div>

          <div style="background: #f0f8ff; padding: 20px; border-radius: 10px;">
            <h4>💡 学习提示</h4>
            <p>尝试将这个概念与你熟悉的事物联系起来，这样能帮助你更好地理解和记忆。</p>
          </div>
        </div>
      </div>
    `;
  }

  // 根据知识点标题生成概念图示
  function getConceptDiagram(title) {
    if (title.includes('IoC') || title.includes('Spring') || title.includes('依赖注入')) {
      return `应用程序 → Spring容器 → 管理Bean生命周期 → 依赖注入`;
    } else if (title.includes('多线程') || title.includes('线程')) {
      return `主线程 → 创建子线程 → 线程同步 → 资源共享`;
    } else if (title.includes('集合') || title.includes('List') || title.includes('Map')) {
      return `数据输入 → 集合处理 → 数据输出 → 性能优化`;
    } else if (title.includes('异常') || title.includes('Exception')) {
      return `代码执行 → 异常发生 → 异常处理 → 程序恢复`;
    } else {
      return `输入 → 处理过程 → 输出 → 结果验证`;
    }
  }

  // 动态生成概念内容（备用方案）
  function generateDynamicConcept(title) {
    if (title.includes('IoC') || title.includes('依赖注入')) {
      return 'IoC（控制反转）是一种设计原则，用来将对象的创建和绑定从使用它们的代码中解耦。在传统的程序设计中，我们直接在代码中创建对象，而使用IoC后，对象的创建和管理由容器负责，我们只需要定义好依赖关系即可。';
    } else if (title.includes('多线程')) {
      return '多线程允许程序同时执行多个任务，提高CPU利用率和程序响应性。通过创建多个线程，可以让程序在执行耗时操作时仍能响应用户交互，或者利用多核CPU的优势并行处理任务。';
    } else if (title.includes('集合')) {
      return '集合框架提供了一系列用于存储和操作数据组的数据结构。不同的集合类有不同的特性和适用场景，如List适合有序存储，Set适合去重存储，Map适合键值对存储。';
    }
    return `让我们深入理解 ${title} 的核心概念和基本原理。这个概念在软件开发中扮演着重要角色，掌握它对于提升编程能力至关重要。`;
  }

  // 动态生成类比内容（备用方案）
  function generateDynamicAnalogy(title) {
    if (title.includes('IoC') || title.includes('依赖注入')) {
      return 'IoC就像餐厅的点餐系统：传统方式是你自己去厨房点菜（直接创建对象），而IoC是你告诉服务员（容器），服务员帮你协调一切。你不需要关心菜是怎么做的，只需要享受美食（使用对象）。';
    } else if (title.includes('多线程')) {
      return '多线程就像厨房里的多位厨师：单线程就像只有一位厨师，他必须一道菜一道菜地做；而多线程就像有多位厨师，他们可以同时准备不同的菜品，大大提高效率。';
    } else if (title.includes('集合')) {
      return '集合就像不同的储物容器：List就像书架，书按顺序摆放；Set就像储物箱，每个物品只放一次；Map就像带标签的储物柜，通过标签快速找到物品。';
    }
    return `想象一下 ${title} 就像日常生活中的某个场景，通过这种类比可以帮助你更好地理解这个抽象概念的实际应用和意义。`;
  }

  // 渲染API概览内容
  function renderOverviewContent() {
    return `
      <div class="concept-content">
        <h3>📋 ${currentState.currentContent.title} API概览</h3>
        <p>了解${currentState.currentContent.title}的主要功能和用途</p>

        <div class="concept-visual">
          <h4>🔧 主要功能</h4>
          <ul style="text-align: left; line-height: 1.8;">
            <li>核心功能1：描述功能用途</li>
            <li>核心功能2：描述功能用途</li>
            <li>核心功能3：描述功能用途</li>
          </ul>
        </div>
      </div>
    `;
  }

  // 渲染使用示例内容
  function renderUsageContent() {
    return `
      <div class="code-exercise">
        <h3>🔧 ${currentState.currentContent.title} 使用示例</h3>
        <div class="code-prompt">
          <p><strong>示例：</strong>${currentState.currentContent.title}的基本使用方法</p>
        </div>

        <div class="desktop-code-editor">
          <pre style="background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace;">
// ${currentState.currentContent.title} 使用示例
public class Example {
    public static void main(String[] args) {
        // 在这里展示使用示例
        System.out.println("示例代码");
    }
}</pre>
        </div>
      </div>
    `;
  }

  // 渲染桌面端代码练习
  function renderDesktopCodingContent() {
    return `
      <div class="code-exercise">
        <h3>💻 代码实践：${currentState.currentContent.title}</h3>

        <div class="code-prompt">
          <p><strong>任务：</strong>完成以下代码实现，理解${currentState.currentContent.title}的核心概念</p>
        </div>

        <div class="desktop-code-editor">
          <div style="background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace;">
            <div class="code-line"><span style="color: #569cd6;">public class</span> <span style="color: #4ec9b0;">Practice</span> {</div>
            <div class="code-line">&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #569cd6;">public static void</span> <span style="color: #dcdcaa;">main</span>(String[] args) {</div>
            <div class="code-line">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<textarea placeholder="// 在这里实现代码逻辑" style="width: 100%; background: #1e1e1e; color: #f8f8f2; border: 1px solid #444; padding: 8px; border-radius: 4px; min-height: 80px; font-family: 'Courier New', monospace;"></textarea></div>
            <div class="code-line">&nbsp;&nbsp;&nbsp;&nbsp;}</div>
            <div class="code-line">}</div>
          </div>
        </div>

        <div style="margin-top: 20px;">
          <button class="action-btn btn-next" onclick="runCode()" style="background: var(--info-color);">
            🔧 运行测试
          </button>
        </div>
      </div>
    `;
  }

  // 渲染移动端代码构建器
  function renderMobileCodingContent() {
    return `
      <div class="code-exercise">
        <h3>📱 代码构建：${currentState.currentContent.title}</h3>

        <div class="code-prompt">
          <p><strong>任务：</strong>通过拖拽代码块理解${currentState.currentContent.title}的实现</p>
        </div>

        <div class="mobile-code-builder">
          <h4>可用代码块：</h4>
          <div class="code-blocks">
            <div class="code-block" draggable="true" data-code="// 代码块1">代码块1</div>
            <div class="code-block" draggable="true" data-code="// 代码块2">代码块2</div>
            <div class="code-block" draggable="true" data-code="// 代码块3">代码块3</div>
            <div class="code-block" draggable="true" data-code="// 代码块4">代码块4</div>
          </div>

          <h4 style="margin-top: 20px;">代码工作区：</h4>
          <div class="code-workspace">
            <div class="code-line">
              <span class="line-number">1</span>
              <span>public class Practice {</span>
            </div>
            <div class="code-line">
              <span class="line-number">2</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;public static void main(String[] args) {</span>
            </div>
            <div class="code-line">
              <span class="line-number">3</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <div class="code-slot" id="slot1" ondrop="dropCode(event)" ondragover="allowDrop(event)"></div>
            </div>
            <div class="code-line">
              <span class="line-number">4</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;}</span>
            </div>
            <div class="code-line">
              <span class="line-number">5</span>
              <span>}</span>
            </div>
          </div>
        </div>

        <div style="margin-top: 20px;">
          <button class="action-btn btn-next" onclick="checkMobileCode()" style="background: var(--info-color);">
            ✅ 检查答案
          </button>
        </div>
      </div>
    `;
  }

  // ========== 修改后的测验内容，实现逐题展示 ==========
  function renderQuizContent() {
    return `
      <div class="quiz-container">
        <h3>🎯 随堂练习</h3>
        <p>完成以下题目来检验你的理解程度</p>

        <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
          <h4>📝 练习说明</h4>
          <ul style="margin: 10px 0; padding-left: 20px;">
            <li>本练习包含选择题、填空题等题型</li>
            <li>点击题目编号可以快速跳转</li>
            <li>标记重要题目便于复习</li>
            <li>完成所有题目后才能提交</li>
          </ul>
        </div>

        <!-- 题目状态指示器 -->
        <div class="question-status-indicator" id="questionStatusIndicator">
          <!-- 动态生成状态点 -->
        </div>

        <div id="quizQuestionsContainer">
          <div class="loading-text">
            <div style="font-size: 48px; margin-bottom: 20px;">⏳</div>
            <p>加载题目中...</p>
          </div>
        </div>

        <!-- 测验导航 -->
        <div class="quiz-navigation">
          <div class="quiz-progress" id="quizProgress">
            题目 1 / 0
          </div>
          <div class="quiz-controls">
            <button class="mark-btn" id="markBtn" onclick="toggleMarkQuestion()">
              📌 标记
            </button>
            <button class="explanation-btn" onclick="toggleExplanation()">
              💡 查看解析
            </button>
            <button class="action-btn btn-prev" onclick="previousQuestion()" id="prevQuestionBtn">
              ← 上一题
            </button>
            <button class="action-btn btn-next" onclick="nextQuestion()" id="nextQuestionBtn">
              下一题 →
            </button>
          </div>
        </div>

        <!-- 完成按钮 -->
        <div style="text-align: center; margin-top: 30px; display: none;" id="completeQuizSection">
          <button class="quiz-complete-btn" onclick="completeQuiz()" id="completeQuizBtn" disabled>
            ✅ 完成测验
          </button>
          <p style="color: #666; margin-top: 10px; font-size: 14px;" id="completeHint">
            请完成所有题目后再提交
          </p>
        </div>
      </div>
    `;
  }

  function loadQuizQuestions() {
    console.log('开始加载测验题目，知识点ID:', currentState.pointId);

    // 显示加载状态
    const container = document.getElementById('quizQuestionsContainer');
    if (container) {
      container.innerHTML = `
            <div class="loading-text">
                <div style="font-size: 48px; margin-bottom: 20px;">⏳</div>
                <p>正在加载题目...</p>
            </div>
        `;
    }

    fetch('/knowledge/training/' + currentState.pointId + '/quiz-questions')
            .then(response => {
              console.log('响应状态:', response.status, response.statusText);
              if (!response.ok) {
                throw new Error('网络响应不正常，状态码: ' + response.status);
              }
              return response.json();
            })
            .then(data => {
              console.log('收到测验题目完整数据:', data);
              console.log('请求成功状态:', data.success);
              console.log('题目数量:', data.questions ? data.questions.length : 0);

              if (data.success && data.questions && data.questions.length > 0) {
                // 详细检查第一个题目的结构
                const firstQuestion = data.questions[0];
                console.log('第一个题目的完整结构:', firstQuestion);
                console.log('第一个题目的options字段:', firstQuestion.options);
                console.log('options字段类型:', typeof firstQuestion.options);
                console.log('options字段长度:', firstQuestion.options ? firstQuestion.options.length : 0);

                // 检查options字段是否可以正常解析
                if (firstQuestion.options) {
                  try {
                    const testOptions = JSON.parse(firstQuestion.options);
                    console.log('options解析成功:', testOptions);
                    console.log('解析后的类型:', Array.isArray(testOptions) ? '数组' : typeof testOptions);
                    if (Array.isArray(testOptions)) {
                      console.log('数组长度:', testOptions.length);
                      testOptions.forEach((opt, idx) => {
                        console.log(`选项${idx}:`, opt, '类型:', typeof opt);
                      });
                    }
                  } catch (e) {
                    console.error('options解析测试失败:', e);
                    console.error('原始options内容:', firstQuestion.options);

                    // 尝试其他解析方式
                    console.log('尝试直接使用options:', firstQuestion.options);
                  }
                } else {
                  console.warn('第一个题目没有options字段或为空');
                }

                currentState.quiz.questions = data.questions;
                console.log('成功加载题目数量:', data.questions.length);
                renderCurrentQuestion();
                updateQuizNavigation();
                updateQuestionStatusIndicator();
              } else {
                console.warn('没有找到题目或题目为空:', {
                  success: data.success,
                  questionsCount: data.questions ? data.questions.length : 0,
                  message: data.message
                });
                document.getElementById('quizQuestionsContainer').innerHTML =
                        '<div class="no-points" style="text-align: center; padding: 40px 20px; color: #666;">' +
                        '<div style="font-size: 48px; margin-bottom: 20px;">📝</div>' +
                        '<p>暂无测验题目</p>' +
                        '<p style="font-size: 14px; margin-top: 10px;">' +
                        (data.message || '请联系管理员添加题目') + '</p>' +
                        '</div>';
              }
            })
            .catch(error => {
              console.error('加载题目失败:', error);
              document.getElementById('quizQuestionsContainer').innerHTML =
                      '<div class="error-text" style="text-align: center; padding: 40px 20px; color: #f44336;">' +
                      '<div style="font-size: 48px; margin-bottom: 20px;">❌</div>' +
                      '<p>加载题目失败: ' + error.message + '</p>' +
                      '<button class="retry-btn" onclick="retryLoadQuiz()" ' +
                      'style="margin-top: 10px; padding: 8px 20px; background: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">' +
                      '重新加载</button>' +
                      '</div>';
            });
  }

  // 重试加载测验题目
  function retryLoadQuiz() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    loadStageContent(pathConfig.stages[currentState.currentStage]);
  }

  // 渲染当前题目
  function renderCurrentQuestion() {
    const questions = currentState.quiz.questions;
    const currentIndex = currentState.quiz.currentQuestionIndex;

    console.log('渲染当前题目，索引:', currentIndex, '总题目数:', questions.length);

    if (questions.length === 0 || currentIndex >= questions.length) {
      console.warn('没有题目可渲染或索引越界');
      return;
    }

    const question = questions[currentIndex];
    const questionText = question.content || '暂无题目内容';
    const questionType = mapQuestionType(question.questionType);

    console.log('当前题目详情:', {
      索引: currentIndex,
      题型: questionType,
      题目内容: questionText,
      选项字段: question.options,
      选项类型: typeof question.options
    });

    let questionHTML = `
      <div class="quiz-question" data-question-index="${currentIndex}" data-question-type="${questionType}">
        <div class="question-header">
          <span class="question-number">${currentIndex + 1}. ${getQuestionTypeLabel(question.questionType)}</span>
        </div>
        <div class="question-text">${questionText}</div>
        <div class="options-container">
    `;

    // 根据题型渲染不同的交互界面
    switch(questionType) {
      case 'single_choice':
        questionHTML += renderSingleChoiceOptions(question, currentIndex);
        break;

      case 'multiple_choice':
        questionHTML += renderMultipleChoiceOptions(question, currentIndex);
        break;

      case 'fill_blank':
        questionHTML += renderFillBlankOptions(question, currentIndex);
        break;

      case 'true_false':
        questionHTML += renderTrueFalseOptions(question, currentIndex);
        break;

      default:
        questionHTML += `<p style="color: orange;">暂不支持该题型: ${question.questionType}</p>`;
    }

    questionHTML += `
        </div>
        ${question.explanation ? `
          <div class="question-explanation ${currentState.quiz.showExplanations[currentIndex] ? 'show' : ''}" id="explanation-${currentIndex}">
            <strong>💡 题目解析:</strong> ${question.explanation}
          </div>
        ` : ''}
      </div>
    `;

    document.getElementById('quizQuestionsContainer').innerHTML = questionHTML;
    console.log('题目渲染完成');
  }

  function renderSingleChoiceOptions(question, questionIndex) {
    let optionsHTML = '<div style="margin-bottom: 15px; color: #666; font-size: 14px;">📝 单选题（选择最合适的答案）</div>';

    if (!question.options) {
      console.warn('单选题缺少options字段');
      return '<p style="color: orange;">题目缺少选项</p>';
    }

    try {
      let options = [];
      const currentAnswer = currentState.quiz.answers[questionIndex];

      // 增强的选项解析逻辑
      if (Array.isArray(question.options)) {
        // 如果已经是数组格式，直接使用
        options = question.options;
      } else if (typeof question.options === 'string') {
        try {
          // 尝试解析JSON字符串
          const parsedOptions = JSON.parse(question.options);

          if (Array.isArray(parsedOptions)) {
            // 如果是数组格式
            options = parsedOptions;
          } else if (typeof parsedOptions === 'object' && parsedOptions !== null) {
            // 如果是对象格式 {A: "内容", B: "内容"}
            options = Object.entries(parsedOptions).map(([key, value]) => {
              return `${key}. ${value}`;
            });
            console.log('对象格式选项转换结果:', options);
          }
        } catch (jsonError) {
          console.warn('JSON解析失败，尝试其他格式:', jsonError);
          // 尝试逗号分隔格式
          options = parseCommaSeparatedOptions(question.options);
        }
      }

      if (options.length === 0) {
        return '<p style="color: orange;">暂无选项</p>';
      }

      // 渲染选项
      options.forEach((option, optIndex) => {
        const optionLabel = String.fromCharCode(65 + optIndex); // A, B, C, D
        let optionText = option;

        // 处理选项文本
        if (typeof option === 'string') {
          // 如果选项已经是 "A. 内容" 格式，直接使用
          if (option.match(/^[A-Z]\.\s/)) {
            optionText = option;
          } else {
            optionText = `${optionLabel}. ${option}`;
          }
        } else if (option && typeof option === 'object') {
          optionText = option.text || option.content || option.label || '选项内容缺失';
          optionText = `${optionLabel}. ${optionText}`;
        }

        const isSelected = currentAnswer === optionLabel;

        optionsHTML += `
                <div class="option ${isSelected ? 'selected' : ''}"
                     onclick="selectSingleOption(this, ${questionIndex}, '${optionLabel}')">
                    <input type="radio" name="question-${questionIndex}"
                           value="${optionLabel}" ${isSelected ? 'checked' : ''}
                           style="margin-right: 8px;">
                    ${optionText}
                </div>
            `;
      });

    } catch (e) {
      console.error('渲染单选题选项时发生错误:', e);
      optionsHTML = `
            <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107;">
                <p><strong>⚠️ 选项解析错误</strong></p>
                <p>无法正确显示题目选项，但你可以继续回答其他题目。</p>
                <p><small>错误详情: ${e.message}</small></p>
                <p><small>原始选项数据: ${JSON.stringify(question.options)}</small></p>
            </div>
        `;
    }

    return optionsHTML;
  }

  // 修改 renderMultipleChoiceOptions 函数
  function renderMultipleChoiceOptions(question, questionIndex) {
    let optionsHTML = '<div style="margin-bottom: 15px; color: #666; font-size: 14px;">📝 多选题（选择所有合适的答案）</div>';

    if (!question.options) {
      console.warn('多选题缺少options字段');
      return '<p style="color: orange;">题目缺少选项</p>';
    }

    try {
      let options = [];

      // 增强的选项解析逻辑
      if (Array.isArray(question.options)) {
        // 如果已经是数组格式，直接使用
        options = question.options;
      } else if (typeof question.options === 'string') {
        try {
          // 尝试解析JSON字符串
          const parsedOptions = JSON.parse(question.options);

          if (Array.isArray(parsedOptions)) {
            // 如果是数组格式
            options = parsedOptions;
          } else if (typeof parsedOptions === 'object' && parsedOptions !== null) {
            // 如果是对象格式 {A: "内容", B: "内容"}
            options = Object.entries(parsedOptions).map(([key, value]) => {
              return `${key}. ${value}`;
            });
            console.log('对象格式选项转换结果:', options);
          }
        } catch (jsonError) {
          console.warn('JSON解析失败，尝试其他格式:', jsonError);
          // 尝试逗号分隔格式
          options = parseCommaSeparatedOptions(question.options);
        }
      }

      if (options.length === 0) {
        return '<p style="color: orange;">暂无选项</p>';
      }

      const currentAnswers = currentState.quiz.answers[questionIndex] || [];

      // 渲染选项
      options.forEach((option, optIndex) => {
        const optionLabel = String.fromCharCode(65 + optIndex); // A, B, C, D
        let optionText = option;

        // 处理选项文本
        if (typeof option === 'string') {
          // 如果选项已经是 "A. 内容" 格式，直接使用
          if (option.match(/^[A-Z]\.\s/)) {
            optionText = option;
          } else {
            optionText = `${optionLabel}. ${option}`;
          }
        } else if (option && typeof option === 'object') {
          optionText = option.text || option.content || option.label || '选项内容缺失';
          optionText = `${optionLabel}. ${optionText}`;
        }

        const isSelected = Array.isArray(currentAnswers) && currentAnswers.includes(optionLabel);

        optionsHTML += `
        <div class="option ${isSelected ? 'selected' : ''}"
             onclick="selectMultipleOption(this, ${questionIndex}, '${optionLabel}')">
          <input type="checkbox" name="question-${questionIndex}"
                 value="${optionLabel}" ${isSelected ? 'checked' : ''}
                 style="margin-right: 8px;">
          ${optionText}
        </div>
      `;
      });

    } catch (e) {
      console.error('渲染多选题选项时发生错误:', e);
      optionsHTML = `
      <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107;">
        <p><strong>⚠️ 选项解析错误</strong></p>
        <p>无法正确显示题目选项。</p>
        <p><small>错误详情: ${e.message}</small></p>
      </div>
    `;
    }

    return optionsHTML;
  }

  // 新增：解析逗号分隔的选项
  function parseCommaSeparatedOptions(optionsString) {
    console.log('开始解析逗号分隔选项:', optionsString);

    if (!optionsString || typeof optionsString !== 'string') {
      return [];
    }

    // 清理字符串：移除多余空格和引号
    const cleanString = optionsString.trim().replace(/^"+|"+$/g, '');

    // 按逗号分割，并过滤空值
    const options = cleanString.split(',').map(opt => opt.trim()).filter(opt => opt.length > 0);

    console.log('逗号分隔解析结果:', options);
    return options;
  }

  // 新增：渲染填空题
  function renderFillBlankOptions(question, questionIndex) {
    const questionText = question.content || '';
    const blankCount = (questionText.match(/_{3,}/g) || []).length;
    const actualBlankCount = blankCount > 0 ? blankCount : 1;
    const currentAnswers = currentState.quiz.answers[questionIndex] || Array(actualBlankCount).fill('');

    let optionsHTML = `
        <div class="fill-blank-container" style="margin-top: 10px;">
            <div class="blank-hint" style="font-size: 12px; color: #666; margin-bottom: 8px;">
                请在下方填写 ${actualBlankCount} 个空白的答案：
            </div>
    `;

    for (let i = 0; i < actualBlankCount; i++) {
      const answer = currentAnswers[i] || '';
      optionsHTML += `
            <div style="margin-bottom: 8px;">
                <label style="display: block; margin-bottom: 4px; font-size: 14px;">空白 ${i + 1}:</label>
                <input type="text" class="blank-answer" data-blank-index="${i}"
                       value="${answer}"
                       oninput="updateFillBlankAnswer(${questionIndex}, ${i}, this.value)"
                       placeholder="请输入答案..."
                       style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px;">
            </div>
        `;
    }

    optionsHTML += `</div>`;
    return optionsHTML;
  }

  // 新增：渲染判断题
  function renderTrueFalseOptions(question, questionIndex) {
    const trueFalseAnswer = currentState.quiz.answers[questionIndex] || '';

    return `
        <div class="options-container">
            <div class="option ${trueFalseAnswer === 'true' ? 'selected' : ''}" onclick="selectTrueFalse(${questionIndex}, 'true')">
                <input type="radio" name="question-${questionIndex}" value="true" ${trueFalseAnswer === 'true' ? 'checked' : ''} style="margin-right: 8px;">
                正确
            </div>
            <div class="option ${trueFalseAnswer === 'false' ? 'selected' : ''}" onclick="selectTrueFalse(${questionIndex}, 'false')">
                <input type="radio" name="question-${questionIndex}" value="false" ${trueFalseAnswer === 'false' ? 'checked' : ''} style="margin-right: 8px;">
                错误
            </div>
        </div>
    `;
  }
  function tryAlternativeOptionParsing(options, questionIndex, questionType) {
    let html = '';
    console.log('尝试备选解析方案，原始options:', options);

    if (!options) {
      return '<p style="color: red;">选项数据为空</p>';
    }

    // 尝试处理字符串格式的选项（如："A.选项1,B.选项2,C.选项3"）
    if (typeof options === 'string') {
      // 移除可能的前后空格和引号
      const cleanOptions = options.trim().replace(/^"+|"+$/g, '');

      // 尝试按逗号分割
      const optionArray = cleanOptions.split(',').filter(opt => opt.trim());

      if (optionArray.length > 0) {
        optionArray.forEach((option, index) => {
          const optionLabel = String.fromCharCode(65 + index);
          // 移除选项标签（如"A."）
          const optionText = option.replace(/^[A-Z]\.\s*/, '').trim();

          html += `
          <div class="option" onclick="selectSingleOption(this, ${questionIndex}, '${optionLabel}')">
            <input type="radio" name="question-${questionIndex}" value="${optionLabel}" style="margin-right: 8px;">
            ${optionLabel}. ${optionText || '选项内容缺失'}
          </div>
        `;
        });
        return html;
      }
    }

    // 如果所有尝试都失败
    return '<p style="color: red;">无法解析选项格式，请联系管理员</p>';
  }

  // 判断题选择处理
  function selectTrueFalse(questionIndex, value) {
    currentState.quiz.answers[questionIndex] = value;

    // 更新UI
    const options = document.querySelectorAll(`.quiz-question[data-question-index="${questionIndex}"] .option`);
    options.forEach(opt => opt.classList.remove('selected'));

    const selectedOption = document.querySelector(`.quiz-question[data-question-index="${questionIndex}"] .option input[value="${value}"]`);
    if (selectedOption) {
      selectedOption.parentElement.classList.add('selected');
    }

    updateQuizNavigation();
    updateQuestionStatusIndicator();
  }

  // 更新题目状态指示器
  function updateQuestionStatusIndicator() {
    const questions = currentState.quiz.questions;
    const indicator = document.getElementById('questionStatusIndicator');

    if (!indicator || questions.length === 0) return;

    let indicatorHTML = '';
    questions.forEach((_, index) => {
      const isAnswered = currentState.quiz.answers[index] !== undefined;
      const isCurrent = index === currentState.quiz.currentQuestionIndex;
      const isMarked = currentState.quiz.markedQuestions.has(index);

      let className = 'status-dot';
      if (isCurrent) className += ' current';
      if (isAnswered) className += ' answered';
      if (isMarked) className += ' marked';

      indicatorHTML += `<div class="${className}" onclick="goToQuestion(${index})" title="题目 ${index + 1}"></div>`;
    });

    indicator.innerHTML = indicatorHTML;
  }

  // 更新测验导航
  function updateQuizNavigation() {
    const questions = currentState.quiz.questions;
    const currentIndex = currentState.quiz.currentQuestionIndex;
    const totalQuestions = questions.length;

    // 更新进度文本
    document.getElementById('quizProgress').textContent = `题目 ${currentIndex + 1} / ${totalQuestions}`;

    // 更新按钮状态
    document.getElementById('prevQuestionBtn').disabled = currentIndex === 0;
    document.getElementById('nextQuestionBtn').style.display = currentIndex < totalQuestions - 1 ? 'block' : 'none';

    // 更新标记按钮状态
    const markBtn = document.getElementById('markBtn');
    if (markBtn) {
      const isMarked = currentState.quiz.markedQuestions.has(currentIndex);
      markBtn.innerHTML = isMarked ? '✅ 已标记' : '📌 标记';
      markBtn.className = isMarked ? 'mark-btn marked' : 'mark-btn';
    }

    // 显示/隐藏完成区域
    const completeSection = document.getElementById('completeQuizSection');
    const completeBtn = document.getElementById('completeQuizBtn');
    const completeHint = document.getElementById('completeHint');

    if (currentIndex === totalQuestions - 1) {
      completeSection.style.display = 'block';

      // 检查是否所有题目都已回答
      const allAnswered = checkAllQuestionsAnswered();
      completeBtn.disabled = !allAnswered;
      completeHint.textContent = allAnswered ?
              '所有题目已完成，可以提交测验' :
              '请完成所有题目后再提交';
    } else {
      completeSection.style.display = 'none';
    }
  }

  // 检查所有题目是否已回答
  function checkAllQuestionsAnswered() {
    const questions = currentState.quiz.questions;
    for (let i = 0; i < questions.length; i++) {
      if (currentState.quiz.answers[i] === undefined) {
        return false;
      }
    }
    return true;
  }

  // 题目导航函数
  function goToQuestion(index) {
    if (index >= 0 && index < currentState.quiz.questions.length) {
      currentState.quiz.currentQuestionIndex = index;
      renderCurrentQuestion();
      updateQuizNavigation();
      updateQuestionStatusIndicator();
    }
  }

  function previousQuestion() {
    if (currentState.quiz.currentQuestionIndex > 0) {
      currentState.quiz.currentQuestionIndex--;
      renderCurrentQuestion();
      updateQuizNavigation();
      updateQuestionStatusIndicator();
    }
  }

  function nextQuestion() {
    const questions = currentState.quiz.questions;
    if (currentState.quiz.currentQuestionIndex < questions.length - 1) {
      currentState.quiz.currentQuestionIndex++;
      renderCurrentQuestion();
      updateQuizNavigation();
      updateQuestionStatusIndicator();
    }
  }

  // 标记题目功能
  function toggleMarkQuestion() {
    const currentIndex = currentState.quiz.currentQuestionIndex;
    if (currentState.quiz.markedQuestions.has(currentIndex)) {
      currentState.quiz.markedQuestions.delete(currentIndex);
    } else {
      currentState.quiz.markedQuestions.add(currentIndex);
    }
    updateQuizNavigation();
    updateQuestionStatusIndicator();
  }

  // 显示/隐藏解析
  function toggleExplanation() {
    const currentIndex = currentState.quiz.currentQuestionIndex;
    currentState.quiz.showExplanations[currentIndex] = !currentState.quiz.showExplanations[currentIndex];

    const explanation = document.getElementById(`explanation-${currentIndex}`);
    if (explanation) {
      explanation.classList.toggle('show', currentState.quiz.showExplanations[currentIndex]);
    }
  }

  // 答案处理函数
  function selectSingleOption(element, questionIndex, optionValue) {
    // 移除同一问题中其他选项的选中状态
    const questionElement = element.closest('.quiz-question');
    const options = questionElement.querySelectorAll('.option');
    options.forEach(opt => {
      opt.classList.remove('selected');
      const radio = opt.querySelector('input[type="radio"]');
      if (radio) radio.checked = false;
    });

    // 设置当前选项为选中状态
    element.classList.add('selected');
    const radio = element.querySelector('input[type="radio"]');
    if (radio) radio.checked = true;

    // 保存答案
    currentState.quiz.answers[questionIndex] = optionValue;
    updateQuizNavigation();
    updateQuestionStatusIndicator();
  }

  function selectMultipleOption(element, questionIndex, optionValue) {
    // 切换选中状态
    element.classList.toggle('selected');
    const checkbox = element.querySelector('input[type="checkbox"]');
    if (checkbox) {
      checkbox.checked = !checkbox.checked;
    }

    // 保存答案
    const currentAnswers = currentState.quiz.answers[questionIndex] || [];
    let newAnswers;
    if (Array.isArray(currentAnswers)) {
      if (currentAnswers.includes(optionValue)) {
        newAnswers = currentAnswers.filter(val => val !== optionValue);
      } else {
        newAnswers = [...currentAnswers, optionValue];
      }
    } else {
      newAnswers = [optionValue];
    }

    currentState.quiz.answers[questionIndex] = newAnswers;
    updateQuizNavigation();
    updateQuestionStatusIndicator();
  }

  function updateFillBlankAnswer(questionIndex, blankIndex, value) {
    const currentAnswers = currentState.quiz.answers[questionIndex] || [];
    currentAnswers[blankIndex] = value;
    currentState.quiz.answers[questionIndex] = currentAnswers;
    updateQuizNavigation();
    updateQuestionStatusIndicator();
  }

  // 完成测验函数
  function completeQuiz() {
    if (!checkAllQuestionsAnswered()) {
      alert('请完成所有题目后再提交！');
      return;
    }

    // 显示测验结果
    showQuizResults();
  }

  // 显示测验结果
  function showQuizResults() {
    const questions = currentState.quiz.questions;
    let correctCount = 0;
    let resultsHTML = '';

    questions.forEach((question, index) => {
      const userAnswer = currentState.quiz.answers[index];
      const isCorrect = checkAnswerCorrect(question, userAnswer);
      if (isCorrect) correctCount++;

      resultsHTML += `
        <div class="quiz-question" style="margin-bottom: 20px;">
          <div class="question-header">
            <span class="question-number">${index + 1}. ${getQuestionTypeLabel(question.questionType)}</span>
            <span style="color: ${isCorrect ? 'var(--success-color)' : 'var(--danger-color)'};">
              ${isCorrect ? '✅ 正确' : '❌ 错误'}
            </span>
          </div>
          <div class="question-text">${question.content}</div>
          <div style="margin-top: 10px;">
            <strong>你的答案:</strong> ${formatUserAnswer(userAnswer)}<br>
            <strong>正确答案:</strong> ${question.correctAnswer || '暂无标准答案'}
          </div>
          ${question.explanation ? `
            <div class="question-explanation show">
              <strong>💡 题目解析:</strong> ${question.explanation}
            </div>
          ` : ''}
        </div>
      `;
    });

    const score = Math.round((correctCount / questions.length) * 100);

    document.getElementById('quizQuestionsContainer').innerHTML = `
      <div style="text-align: center; padding: 20px;">
        <h3 style="color: var(--success-color);">测验完成！</h3>
        <div style="font-size: 48px; margin: 20px 0;">${score >= 60 ? '🎉' : '😔'}</div>
        <p>你的得分: <strong>${score}分</strong> (${correctCount}/${questions.length})</p>
        <p>${getScoreComment(score)}</p>
      </div>
      ${resultsHTML}
      <div style="text-align: center; margin-top: 30px;">
        <button class="action-btn btn-next" onclick="continueAfterQuiz()" style="background: var(--success-color);">
          继续学习 →
        </button>
      </div>
    `;

    // 隐藏导航和完成区域
    document.querySelector('.quiz-navigation').style.display = 'none';
    document.getElementById('completeQuizSection').style.display = 'none';
    document.getElementById('questionStatusIndicator').style.display = 'none';

    // 标记当前阶段为已完成
    if (!currentState.completedStages.includes(currentState.currentStage)) {
      currentState.completedStages.push(currentState.currentStage);
    }
    updateProgressBar();
  }

  // 辅助函数：检查答案是否正确（需要根据实际业务逻辑实现）
  function checkAnswerCorrect(question, userAnswer) {
    // 这里需要根据题目类型和正确答案进行判断
    // 由于缺少正确答案字段，这里暂时返回true
    return true;
  }

  // 辅助函数：格式化用户答案显示
  function formatUserAnswer(answer) {
    if (Array.isArray(answer)) {
      return answer.join(', ');
    }
    return answer || '未回答';
  }

  // 辅助函数：根据得分给出评语
  function getScoreComment(score) {
    if (score >= 90) return '太棒了！你对这个知识点掌握得很好！';
    if (score >= 70) return '不错！继续加油！';
    if (score >= 60) return '及格了，建议再复习一下相关内容。';
    return '需要加强学习，建议重新学习这个知识点。';
  }

  // 测验完成后继续学习
  function continueAfterQuiz() {
    // 重新显示学习内容区域
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    loadStageContent(pathConfig.stages[currentState.currentStage]);
  }

  // 题型映射函数 - 修复：支持小写题型
  function mapQuestionType(dbQuestionType) {
    // 将输入转换为小写进行比较
    const type = dbQuestionType.toLowerCase();

    const typeMap = {
      'single_choice': 'single_choice',
      'multiple_choice': 'multiple_choice',
      'fill_blank': 'fill_blank',
      'true_false': 'true_false'
    };

    return typeMap[type] || 'unknown';
  }

  // 获取题型显示标签
  function getQuestionTypeLabel(dbQuestionType) {
    const type = dbQuestionType.toLowerCase();

    const labelMap = {
      'single_choice': '单选题',
      'multiple_choice': '多选题',
      'fill_blank': '填空题',
      'true_false': '判断题'
    };

    return labelMap[type] || '未知题型';
  }

  // ========== 优化：学习笔记和问题记录功能 ==========
  // 优化问题记录时的答案框显示和提示
  function selectNoteType(type) {
    currentState.currentNoteType = type;

    // 更新按钮状态
    document.querySelectorAll('.note-type-btn').forEach(btn => {
      btn.classList.remove('active');
    });
    document.querySelector(`.note-type-btn[data-type="${type}"]`).classList.add('active');

    // 根据类型显示或隐藏答案输入框
    const answerInput = document.getElementById('answerInput');
    if (type === 'question') {
      answerInput.style.display = 'block';
      document.getElementById('noteInput').placeholder = '记录你的问题或疑问...';

      // 添加鼓励提示
      const answerLabel = document.querySelector('.answer-label');
      if (answerLabel) {
        answerLabel.innerHTML = '💬 试着去解决这个问题，会让你提高更快哦！';
      }
    } else {
      answerInput.style.display = 'none';
      document.getElementById('noteInput').placeholder = '记录你的学习心得或总结...';
    }
  }

  // 切换笔记区域显示/隐藏
  function toggleNotes() {
    const container = document.getElementById('learningNotesContainer');
    const form = document.getElementById('notesForm');
    const list = document.getElementById('notesList');
    const progress = document.getElementById('notesProgress');
    const toggleBtn = document.getElementById('notesToggle');

    if (form.style.display === 'none') {
      form.style.display = 'block';
      list.style.display = 'block';
      progress.style.display = 'flex';
      toggleBtn.innerHTML = '<span>收起</span> <span>▲</span>';
    } else {
      form.style.display = 'none';
      list.style.display = 'none';
      progress.style.display = 'none';
      toggleBtn.innerHTML = '<span>展开</span> <span>▼</span>';
    }
  }

  // 添加笔记
  function addNote() {
    const noteInput = document.getElementById('noteInput');
    const noteText = noteInput.value.trim();

    if (!noteText) {
      alert('请输入笔记内容');
      return;
    }

    // 创建新笔记对象
    const newNote = {
      id: Date.now(), // 使用时间戳作为ID
      stage: currentState.currentStage,
      type: currentState.currentNoteType,
      text: noteText,
      resolved: false,
      pending: false, // 新增 pending 字段
      showAnswerInput: false,
      timestamp: new Date().toLocaleString()
    };

    // 如果是问题，添加答案
    if (currentState.currentNoteType === 'question') {
      const answerText = document.getElementById('answerText').value.trim();
      newNote.answer = answerText;
      // 解决状态逻辑：有答案=已解决，无答案=待解决
      newNote.resolved = !!answerText; // 有答案就标记为已解决

    }

    // 添加到笔记数组
    currentState.notes.push(newNote);

    // 清空输入框
    noteInput.value = '';
    document.getElementById('answerText').value = '';

    // 重新渲染笔记列表
    renderNotes();

    // 保存到后端
    saveNoteToServer(newNote);
  }

  // 保存笔记到服务器
  function saveNoteToServer(note) {
    const formData = new FormData();
    formData.append('pointId', currentState.pointId);
    formData.append('note', JSON.stringify(note));

    fetch('/knowledge/training/save-note', {
      method: 'POST',
      body: formData
    })
            .then(response => response.text())
            .then(result => {
              if (result !== 'success') {
                console.error('保存笔记失败:', result);
              }
            })
            .catch(error => {
              console.error('保存笔记失败:', error);
            });
  }

  // 清空笔记输入
  function clearNote() {
    document.getElementById('noteInput').value = '';
    document.getElementById('answerText').value = '';
  }

  // 渲染笔记列表
  function renderNotes() {
    const notesList = document.getElementById('notesList');
    const currentStageNotes = currentState.notes.filter(note => note.stage === currentState.currentStage);

    if (currentStageNotes.length === 0) {
      notesList.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">暂无笔记，开始记录你的学习思考吧！</div>';
      updateNotesProgress();
      return;
    }

    let notesHTML = '';

    currentStageNotes.forEach(note => {
      const resolvedClass = note.resolved ? 'resolved' : '';
      const typeClass = note.type;
      const typeText = note.type === 'question' ? '问题' : '心得';

      // 修改这部分，将状态标签移到问题文本之前
      notesHTML += `
    <div class="note-item ${typeClass} ${resolvedClass}" id="note-${note.id}" style="display: flex; flex-direction: column;">
        <div class="note-content" style="flex: 1;">
            <div class="note-type-badge ${typeClass}">${typeText}</div>

            <!-- 问题状态显示 - 移到问题文本之前 -->
            ${note.type === 'question' ? `
                <div class="question-status" style="margin: 8px 0; display: flex; align-items: center; gap: 10px;">
                    <span class="status-badge ${note.resolved ? 'resolved' : note.pending ? 'pending' : 'unsolved'}"
                          style="padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: bold;
                                 ${note.resolved ? 'background: #d4edda; color: #155724;' :
              note.pending ? 'background: #fff3cd; color: #856404;' :
                      'background: #f8d7da; color: #721c24;'}">
                        ${note.resolved ? '✅ 已解决' : note.pending ? '⏸️ 待定' : '❓ 待解决'}
                    </span>
                    ${!note.resolved && !note.pending ? `
                        <button class="start-resolve-btn" onclick="startResolving(${note.id})"
                                style="background: var(--warning-color); color: white; border: none; padding: 6px 12px; border-radius: 4px; font-size: 12px; cursor: pointer;">
                            开始解决
                        </button>
                        <button class="skip-resolve-btn" onclick="skipResolving(${note.id})"
                                style="background: #6c757d; color: white; border: none; padding: 6px 12px; border-radius: 4px; font-size: 12px; cursor: pointer;">
                            暂不解决
                        </button>
                    ` : ''}
                </div>
            ` : ''}

            <div class="note-text">${note.text}</div>

            ${note.answer ? `
                <div class="note-answer" style="background: #e7f3ff; padding: 10px; border-radius: 6px; margin-top: 10px; border-left: 3px solid var(--info-color);">
                    <div class="note-answer-label" style="font-weight: bold; color: #0c5460; margin-bottom: 5px;">💡 我的解答：</div>
                    <div style="line-height: 1.5;">${note.answer}</div>
                </div>
            ` : ''}

            <div class="note-meta" style="font-size: 12px; color: #6c757d; margin-top: 8px;">记录于: ${note.timestamp}</div>
        </div>

        <!-- 答案输入区域 -->
        ${note.showAnswerInput ? `
            <div class="answer-input-area" style="margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 6px; width: 100%; box-sizing: border-box;">
                ${note.isEditing ? `
                    <div style="font-weight: bold; margin-bottom: 8px; color: #333;">✏️ 编辑问题和解答：</div>
                    <textarea id="edit-question-${note.id}"
                              style="width: 100%; min-height: 80px; padding: 12px; border: 1px solid #ddd; border-radius: 6px; margin-bottom: 12px; font-family: inherit; font-size: 14px; resize: vertical; box-sizing: border-box;"
                              placeholder="编辑你的问题...">${note.editText || note.text}</textarea>
                ` : ''}
                <div style="font-weight: bold; margin-bottom: 8px; color: #333;">💡 ${note.isEditing ? '编辑解答' : '写下你的解答'}：</div>
                <textarea id="resolve-answer-${note.id}"
                          style="width: 100%; min-height: ${note.isEditing ? '100px' : '120px'}; padding: 12px; border: 1px solid #ddd; border-radius: 6px; margin-bottom: 12px; font-family: inherit; font-size: 14px; resize: none; box-sizing: border-box;"
                          placeholder="${note.isEditing ? '编辑你的解答...' : '在这里详细写下你的解决方案或思考过程...'}">${note.isEditing ? (note.editAnswer || note.answer || '') : (note.answer || '')}</textarea>
                <div style="display: flex; gap: 10px; justify-content: flex-start;">
                    <button class="action-btn" onclick="${note.isEditing ? 'saveEdit(' + note.id + ')' : 'saveAnswer(' + note.id + ')'}" style="background: var(--success-color); color: white; padding: 10px 20px; font-size: 14px; border: none; border-radius: 6px; cursor: pointer;">
                        ✅ ${note.isEditing ? '保存编辑' : '保存答案'}
                    </button>
                    <button class="action-btn" onclick="cancelResolving(${note.id})" style="background: #6c757d; color: white; padding: 10px 20px; font-size: 14px; border: none; border-radius: 6px; cursor: pointer;">
                        取消
                    </button>
                </div>
            </div>
        ` : ''}

        <div class="note-actions" style="display: flex; gap: 8px; justify-content: flex-end; margin-top: 10px;">
            ${note.type === 'question' && !note.resolved && !note.pending ? `
                <button class="note-action resolve" onclick="markAsResolved(${note.id})" style="background: none; border: none; cursor: pointer; font-size: 14px; padding: 4px; border-radius: 3px; color: var(--success-color);">
                    ✅ 标记为已解决
                </button>
            ` : ''}
            <button class="note-action edit" onclick="editNote(${note.id})" style="background: none; border: none; cursor: pointer; font-size: 14px; padding: 4px; border-radius: 3px; color: var(--info-color);">
                ✏️ 编辑
            </button>
            <button class="note-action delete" onclick="deleteNote(${note.id})" style="background: none; border: none; cursor: pointer; font-size: 14px; padding: 4px; border-radius: 3px; color: var(--danger-color);">
                🗑️ 删除
            </button>
        </div>
    </div>
`;
    });

    notesList.innerHTML = notesHTML;
    updateNotesProgress();
  }

  // 开始解决问题 - 显示答案输入框
  function startResolving(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex !== -1) {
      // 收起顶部学习笔记与问题记录输入框
      const notesForm = document.getElementById('notesForm');
      const notesToggle = document.getElementById('notesToggle');

      if (notesForm) notesForm.style.display = 'none';
      if (notesToggle) notesToggle.innerHTML = '<span>展开</span> <span>▼</span>';

      // 展开当前问题的答案输入框
      currentState.notes[noteIndex].showAnswerInput = true;
      renderNotes();

      // 自动聚焦到答案输入框并设置自适应高度
      setTimeout(() => {
        const answerTextarea = document.getElementById(`resolve-answer-${noteId}`);
        if (answerTextarea) {
          answerTextarea.focus();

          // 设置自适应高度
          answerTextarea.style.height = 'auto';
          answerTextarea.style.height = (answerTextarea.scrollHeight) + 'px';

          // 监听输入变化，自动调整高度
          answerTextarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
          });
        }
      }, 100);
    }
  }

  // 取消解答
  function cancelResolving(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex !== -1) {
      // 如果是编辑模式，恢复原始数据
      if (currentState.notes[noteIndex].isEditing) {
        currentState.notes[noteIndex].showAnswerInput = false;
        currentState.notes[noteIndex].isEditing = false;
        delete currentState.notes[noteIndex].editText;
        delete currentState.notes[noteIndex].editAnswer;
      } else {
        currentState.notes[noteIndex].showAnswerInput = false;
      }

      // 展开顶部学习笔记与问题记录输入框
      const notesForm = document.getElementById('notesForm');
      const notesList = document.getElementById('notesList');
      const notesProgress = document.getElementById('notesProgress');
      const notesToggle = document.getElementById('notesToggle');

      if (notesForm) notesForm.style.display = 'block';
      if (notesList) notesList.style.display = 'block';
      if (notesProgress) notesProgress.style.display = 'flex';
      if (notesToggle) notesToggle.innerHTML = '<span>收起</span> <span>▲</span>';

      renderNotes();
    }
  }

  function saveAnswer(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex === -1) return;

    const answerText = document.getElementById(`resolve-answer-${noteId}`).value.trim();

    if (answerText) {
      // 展开顶部学习笔记与问题记录输入框
      const notesForm = document.getElementById('notesForm');
      const notesList = document.getElementById('notesList');
      const notesProgress = document.getElementById('notesProgress');
      const notesToggle = document.getElementById('notesToggle');

      if (notesForm) notesForm.style.display = 'block';
      if (notesList) notesList.style.display = 'block';
      if (notesProgress) notesProgress.style.display = 'flex';
      if (notesToggle) notesToggle.innerHTML = '<span>收起</span> <span>▲</span>';

      currentState.notes[noteIndex].answer = answerText;
      currentState.notes[noteIndex].resolved = true;
      currentState.notes[noteIndex].showAnswerInput = false;

      renderNotes();
      updateNoteOnServer(currentState.notes[noteIndex]);
      updateNotesProgress();
    } else {
      alert('请输入解答内容');
    }
  }

  // 统一解决状态逻辑
  function markAsResolved(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex !== -1) {
      // 如果有答案内容，自动填充
      if (!currentState.notes[noteIndex].answer) {
        currentState.notes[noteIndex].answer = "我已理解并解决了这个问题";
      }
      currentState.notes[noteIndex].resolved = true;
      currentState.notes[noteIndex].pending = false;
      currentState.notes[noteIndex].showAnswerInput = false;

      renderNotes();
      updateNoteOnServer(currentState.notes[noteIndex]);
      updateNotesProgress();
    }
  }

  function skipResolving(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex !== -1) {
      // 展开顶部学习笔记与问题记录输入框
      const notesForm = document.getElementById('notesForm');
      const notesList = document.getElementById('notesList');
      const notesProgress = document.getElementById('notesProgress');
      const notesToggle = document.getElementById('notesToggle');

      if (notesForm) notesForm.style.display = 'block';
      if (notesList) notesList.style.display = 'block';
      if (notesProgress) notesProgress.style.display = 'flex';
      if (notesToggle) notesToggle.innerHTML = '<span>收起</span> <span>▲</span>';

      // 标记为待定状态
      currentState.notes[noteIndex].pending = true;
      currentState.notes[noteIndex].resolved = false;
      currentState.notes[noteIndex].showAnswerInput = false;

      renderNotes();
      updateNoteOnServer(currentState.notes[noteIndex]);
      updateNotesProgress();

      // 提示用户
      alert('问题已标记为待定状态，你可以在完成学习后回顾这些问题。');
    }
  }

  function editNote(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex === -1) return;

    const note = currentState.notes[noteIndex];

    // 收起顶部学习笔记与问题记录输入框
    const notesForm = document.getElementById('notesForm');
    const notesToggle = document.getElementById('notesToggle');

    if (notesForm) notesForm.style.display = 'none';
    if (notesToggle) notesToggle.innerHTML = '<span>展开</span> <span>▼</span>';

    // 填充编辑表单到当前问题的答案输入框
    const noteIndexInState = currentState.notes.findIndex(n => n.id === noteId);
    if (noteIndexInState !== -1) {
      currentState.notes[noteIndexInState].showAnswerInput = true;
      currentState.notes[noteIndexInState].isEditing = true; // 标记为编辑模式
      currentState.notes[noteIndexInState].editText = note.text; // 保存编辑文本
      currentState.notes[noteIndexInState].editAnswer = note.answer || ''; // 保存编辑答案

      renderNotes();

      // 自动聚焦到答案输入框并设置自适应高度
      setTimeout(() => {
        const answerTextarea = document.getElementById(`resolve-answer-${noteId}`);
        if (answerTextarea) {
          answerTextarea.focus();

          // 设置自适应高度
          answerTextarea.style.height = 'auto';
          answerTextarea.style.height = (answerTextarea.scrollHeight) + 'px';

          // 监听输入变化，自动调整高度
          answerTextarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
          });
        }
      }, 100);
    }
  }

  // 删除笔记
  function deleteNote(noteId) {
    if (confirm('确定要删除这条笔记吗？')) {
      currentState.notes = currentState.notes.filter(note => note.id !== noteId);
      renderNotes();

      // 从服务器删除
      deleteNoteFromServer(noteId);
    }
  }

  // 更新服务器上的笔记
  function updateNoteOnServer(note) {
    const formData = new FormData();
    formData.append('noteId', note.id);
    formData.append('note', JSON.stringify(note));

    fetch('/knowledge/training/update-note', {
      method: 'POST',
      body: formData
    })
            .then(response => response.text())
            .then(result => {
              if (result !== 'success') {
                console.error('更新笔记失败:', result);
              }
            })
            .catch(error => {
              console.error('更新笔记失败:', error);
            });
  }

  // 从服务器删除笔记
  function deleteNoteFromServer(noteId) {
    const formData = new FormData();
    formData.append('noteId', noteId);

    fetch('/knowledge/training/delete-note', {
      method: 'POST',
      body: formData
    })
            .then(response => response.text())
            .then(result => {
              if (result !== 'success') {
                console.error('删除笔记失败:', result);
              }
            })
            .catch(error => {
              console.error('删除笔记失败:', error);
            });
  }

  // 更新笔记进度
  function updateNotesProgress() {
    const progressElement = document.getElementById('notesProgress');
    const currentStageNotes = currentState.notes.filter(note => note.stage === currentState.currentStage);
    const questions = currentStageNotes.filter(note => note.type === 'question');
    const unresolvedQuestions = questions.filter(note => !note.resolved);

    if (unresolvedQuestions.length === 0) {
      progressElement.innerHTML = `
        <i>✅</i>
        <span>所有问题已解决，可以继续学习！</span>
      `;
      progressElement.className = 'notes-progress';
    } else {
      progressElement.innerHTML = `
        <i>⚠️</i>
        <span>已记录 ${questions.length} 个问题，${unresolvedQuestions.length} 个待处理</span>
      `;
      progressElement.className = 'notes-progress warning';
    }
  }

  // 检查是否可以进入下一阶段
  function canProceedToNextStage() {
    const currentStageNotes = currentState.notes.filter(note => note.stage === currentState.currentStage);
    const questions = currentStageNotes.filter(note => note.type === 'question');

    // 只检查未解决且未标记为待定的问题
    const blockingQuestions = questions.filter(note => !note.resolved && !note.pending);

    // 如果有未解决且未标记为待定的问题，不能进入下一阶段
    if (blockingQuestions.length > 0) {
      return false;
    }

    return true;
  }

  // 更新内容显示
  function updateContentDisplay() {
    // 内容已通过Thymeleaf设置，这里主要更新动态部分
  }

  // 更新导航按钮
  function updateNavigationButtons() {
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    prevBtn.disabled = currentState.currentStage === 0;

    if (currentState.currentStage === pathConfig.stages.length - 1) {
      nextBtn.textContent = '完成学习 🎉';
    } else {
      nextBtn.textContent = '下一阶段 →';
    }
  }

  // 上一阶段
  function previousStage() {
    if (currentState.currentStage > 0) {
      currentState.currentStage--;
      renderLearningPath();
      const pathConfig = knowledgeConfigs[currentState.knowledgeType];
      loadStageContent(pathConfig.stages[currentState.currentStage]);
      updateNavigationButtons();
      updateProgressBar();
    }
  }

  // 下一阶段
  function nextStage() {
    // 检查问题框是否有内容，如果有则提示是否清空
    const noteInput = document.getElementById('noteInput');
    if (noteInput && noteInput.value.trim() !== '') {
      if (confirm('问题框中还有未提交的内容，是否清空？\n\n点击"确定"清空内容并继续下一阶段\n点击"取消"保留内容')) {
        // 用户选择清空
        noteInput.value = '';
        const answerInput = document.getElementById('answerText');
        if (answerInput) {
          answerInput.value = '';
          answerInput.style.display = 'none';
        }
      } else {
        // 用户选择不清空，直接返回不进入下一阶段
        return;
      }
    }

    // 检查是否可以进入下一阶段（所有问题是否已解决）
    if (!canProceedToNextStage()) {
      alert('请先解决当前阶段的所有问题后再继续！');
      return;
    }

    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    if (currentState.currentStage < pathConfig.stages.length - 1) {
      currentState.currentStage++;
      renderLearningPath();
      loadStageContent(pathConfig.stages[currentState.currentStage]);
      updateNavigationButtons();
      updateProgressBar();
    } else {
      completeLearning();
    }
  }

  // ========== 完成学习，提交学习记录 ==========
  function completeLearning() {
    const contentArea = document.getElementById('learningContent');
    contentArea.innerHTML = `
        <div style="text-align: center; padding: 40px;">
            <div style="font-size: 64px; margin-bottom: 20px;">🎉</div>
            <h2 style="color: var(--success-color); margin-bottom: 15px;">恭喜完成学习！</h2>
            <p style="color: #666; margin-bottom: 30px;">你已成功掌握 <strong>${currentState.currentContent.title}</strong> 的核心概念</p>

            <div style="margin: 20px 0;">
                <label style="display: block; margin-bottom: 10px;">学习评价：</label>
                <select id="learningRating" style="padding: 8px; border-radius: 4px; border: 1px solid #ddd;">
                    <option value="5">★★★★★ 非常满意</option>
                    <option value="4">★★★★ 满意</option>
                    <option value="3">★★★ 一般</option>
                    <option value="2">★★ 不太满意</option>
                    <option value="1">★ 很不满意</option>
                </select>
            </div>

            <div style="margin: 20px 0;">
                <label style="display: block; margin-bottom: 10px;">学习心得：</label>
                <textarea id="learningNotes" style="width: 100%; min-height: 80px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;"
                          placeholder="记录学习心得..."></textarea>
            </div>

            <div style="margin: 20px 0; text-align: left;">
                <h4>学习过程中记录的问题与心得：</h4>
                <div id="finalNotesList" style="max-height: 200px; overflow-y: auto; margin-top: 10px;">
                    <!-- 最终笔记列表将通过JavaScript动态生成 -->
                </div>
            </div>

            <!-- 修改按钮部分 -->
            <div style="display: flex; gap: 15px; justify-content: center; flex-wrap: wrap;">
                <button class="action-btn" onclick="goToPracticeMode()" style="background: var(--primary-color);">
                    🎯 进入练习模式
                </button>
                <button class="action-btn" onclick="goToPendingQuestions()" style="background: var(--warning-color);">
                    ❓ 去解决待定问题
                </button>
                <button class="action-btn" onclick="restartLearning()" style="background: var(--info-color);">
                    🔄 重新学习
                </button>
                <button class="action-btn" onclick="goToNextPoint()" style="background: var(--success-color);">
                    📚 下一个知识点
                </button>
            </div>
        </div>
    `;

    // 渲染最终笔记列表
    renderFinalNotesList();

    // 隐藏学习过程中的笔记区域
    document.getElementById('learningNotesContainer').style.display = 'none';
    document.querySelector('.action-buttons').style.display = 'none';
  }

  // 渲染最终笔记列表
  function renderFinalNotesList() {
    const finalNotesList = document.getElementById('finalNotesList');

    if (currentState.notes.length === 0) {
      finalNotesList.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">学习过程中未记录任何问题或心得</div>';
      return;
    }

    let notesHTML = '';

    currentState.notes.forEach(note => {
      const resolvedClass = note.resolved ? 'resolved' : '';
      const typeClass = note.type;
      const typeText = note.type === 'question' ? '问题' : '心得';

      notesHTML += `
        <div class="note-item ${typeClass} ${resolvedClass}" style="margin-bottom: 10px;">
          <div class="note-content">
            <div class="note-type-badge ${typeClass}">${typeText}</div>
            <div class="note-text">${note.text}</div>
            ${note.answer ? `
              <div class="note-answer">
                <div class="note-answer-label">💡 我的解答：</div>
                ${note.answer}
              </div>
            ` : ''}
            <div class="note-meta">阶段 ${note.stage + 1} • 记录于: ${note.timestamp}</div>
          </div>
        </div>
      `;
    });

    finalNotesList.innerHTML = notesHTML;
  }

  // 提交学习完成记录
  function submitLearningComplete() {
    const rating = document.getElementById('learningRating').value;
    const notes = document.getElementById('learningNotes').value;

    const formData = new FormData();
    formData.append('pointId', currentState.pointId);
    formData.append('rating', rating);
    formData.append('notes', notes);
    // 添加学习过程中的笔记
    formData.append('learningNotes', JSON.stringify(currentState.notes));

    fetch('/knowledge/training/complete', {
      method: 'POST',
      body: formData
    })
            .then(response => response.text())
            .then(result => {
              if (result === 'success') {
                alert('学习记录提交成功！');
                goToNextPoint();
              } else {
                alert('提交失败：' + result);
              }
            })
            .catch(error => {
              console.error('提交学习记录失败:', error);
              alert('提交失败，请重试');
            });
  }

  // 跳转到练习页面
  function goToPractice() {
    window.location.href = '/practice/gateway/prepare?pointId=' + currentState.pointId;
  }

  // 跳转到下一个知识点
  function goToNextPoint() {
    window.location.href = '/practice/gateway/prepare?pointId='+ (currentState.pointId + 1);
  }

  // 初始化代码块拖拽
  document.addEventListener('DOMContentLoaded', function() {
    const codeBlocks = document.querySelectorAll('.code-block');
    codeBlocks.forEach(block => {
      block.addEventListener('dragstart', function(event) {
        event.dataTransfer.setData("text", event.target.getAttribute('data-code'));
      });
    });
  });

  // 允许拖拽
  function allowDrop(event) {
    event.preventDefault();
  }

  // 处理拖拽放置
  function dropCode(event) {
    event.preventDefault();
    const code = event.dataTransfer.getData("text");
    event.target.textContent = code;
    event.target.className = "code-slot filled";
  }

  // 以下为占位函数，用于未实现的阶段类型
  function renderDefaultContent(stage) {
    return `
      <div class="concept-content">
        <h3>${stage.icon} ${stage.name}</h3>
        <p>${stage.description}</p>
        <div style="text-align: center; padding: 40px; color: #666;">
          <div style="font-size: 48px; margin-bottom: 20px;">🔧</div>
          <p>此阶段内容正在开发中...</p>
        </div>
      </div>
    `;
  }

  function renderPracticeContent() {
    return renderDefaultContent({icon: "💻", name: "动手练习", description: "在实际代码中应用所学知识"});
  }

  function renderVisualizationContent() {
    return renderDefaultContent({icon: "📊", name: "过程可视化", description: "通过动画理解执行过程"});
  }

  function runCode() {
    alert('代码运行功能正在开发中...');
  }

  function checkMobileCode() {
    alert('代码检查功能正在开发中...');
  }

  // 保存编辑
  function saveEdit(noteId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === noteId);
    if (noteIndex === -1) return;

    const questionText = document.getElementById(`edit-question-${noteId}`).value.trim();
    const answerText = document.getElementById(`resolve-answer-${noteId}`).value.trim();

    if (!questionText) {
      alert('问题内容不能为空');
      return;
    }

    // 更新笔记内容
    currentState.notes[noteIndex].text = questionText;
    currentState.notes[noteIndex].answer = answerText;

    // 如果有答案，自动标记为已解决
    if (answerText) {
      currentState.notes[noteIndex].resolved = true;
    }

    // 重置编辑状态
    currentState.notes[noteIndex].showAnswerInput = false;
    currentState.notes[noteIndex].isEditing = false;
    delete currentState.notes[noteIndex].editText;
    delete currentState.notes[noteIndex].editAnswer;

    // 展开顶部表单
    const notesForm = document.getElementById('notesForm');
    const notesList = document.getElementById('notesList');
    const notesProgress = document.getElementById('notesProgress');
    const notesToggle = document.getElementById('notesToggle');

    if (notesForm) notesForm.style.display = 'block';
    if (notesList) notesList.style.display = 'block';
    if (notesProgress) notesProgress.style.display = 'flex';
    if (notesToggle) notesToggle.innerHTML = '<span>收起</span> <span>▲</span>';

    renderNotes();
    updateNoteOnServer(currentState.notes[noteIndex]);
    updateNotesProgress();
  }

  // ========== 新增：学习完成后的操作函数 ==========

  // 进入练习模式
  function goToPracticeMode() {
    console.log("跳转到练习模式选择页面，知识点ID:", currentState.pointId);
    // 跳转到练习模式选择页面
    window.location.href = '/practice/gateway/prepare?pointId=' + currentState.pointId;
  }

  // 去解决待定问题
  function goToPendingQuestions() {
    console.log("查看待定问题");

    // 获取所有待定问题
    const pendingQuestions = currentState.notes.filter(note =>
            note.type === 'question' && note.pending
    );

    if (pendingQuestions.length === 0) {
      alert('🎉 恭喜！没有待定的问题需要解决。');
      return;
    }

    // 显示待定问题列表
    const contentArea = document.getElementById('learningContent');
    let questionsHTML = `
        <div style="padding: 20px;">
            <h3 style="color: var(--warning-color); margin-bottom: 20px;">⏸️ 待定问题列表</h3>
            <p>以下是学习过程中标记为待定的问题，建议先解决这些问题：</p>
    `;

    pendingQuestions.forEach((question, index) => {
      questionsHTML += `
            <div class="note-item question" style="margin: 15px 0; padding: 15px; background: #fff3cd; border-radius: 8px; border-left: 4px solid var(--warning-color);">
                <div style="font-weight: bold; margin-bottom: 8px;">问题 ${index + 1}:</div>
                <div style="margin-bottom: 10px;">${question.text}</div>
                <div style="display: flex; gap: 10px;">
                    <button onclick="resolveQuestionNow(${question.id})"
                            style="padding: 8px 15px; background: var(--success-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
                        ✅ 立即解决
                    </button>
                    <button onclick="removePendingStatus(${question.id})"
                            style="padding: 8px 15px; background: var(--info-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
                        📝 标记为已解决
                    </button>
                </div>
            </div>
        `;
    });

    questionsHTML += `
            <div style="margin-top: 20px; text-align: center;">
                <button onclick="backToCompletion()"
                        style="padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 6px; cursor: pointer;">
                    ← 返回完成页面
                </button>
            </div>
        </div>
    `;

    contentArea.innerHTML = questionsHTML;
  }

  // 立即解决问题
  function resolveQuestionNow(questionId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === questionId);
    if (noteIndex !== -1) {
      currentState.notes[noteIndex].showAnswerInput = true;
      currentState.notes[noteIndex].pending = false;
      renderNotes();

      // 滚动到该问题
      setTimeout(() => {
        const noteElement = document.getElementById(`note-${questionId}`);
        if (noteElement) {
          noteElement.scrollIntoView({ behavior: 'smooth' });
        }
      }, 100);
    }
  }

  // 移除待定状态
  function removePendingStatus(questionId) {
    const noteIndex = currentState.notes.findIndex(note => note.id === questionId);
    if (noteIndex !== -1) {
      currentState.notes[noteIndex].pending = false;
      currentState.notes[noteIndex].resolved = true;
      updateNoteOnServer(currentState.notes[noteIndex]);
      goToPendingQuestions(); // 刷新列表
    }
  }

  // 返回完成页面
  function backToCompletion() {
    completeLearning();
  }

  // 重新学习
  function restartLearning() {
    if (confirm('确定要重新学习这个知识点吗？这将重置你的学习进度。')) {
      // 重置学习状态
      currentState.currentStage = 0;
      currentState.completedStages = [];

      // 重新渲染学习路径
      renderLearningPath();
      updateNavigationButtons();
      updateProgressBar();

      // 加载第一阶段内容
      const pathConfig = knowledgeConfigs[currentState.knowledgeType];
      loadStageContent(pathConfig.stages[0]);

      // 显示学习笔记区域
      document.getElementById('learningNotesContainer').style.display = 'block';
      document.querySelector('.action-buttons').style.display = 'flex';
    }
  }

  // 渲染实际示例内容
  function renderExampleContent() {
    const exampleData = learningContentData.exampleContent ||
            generateDynamicExample(currentState.currentContent.title);

    return `
    <div class="concept-content">
      <h3>📚 ${currentState.currentContent.title} 实际示例</h3>

      <div style="background: #e7f3ff; padding: 20px; border-radius: 10px; margin: 20px 0;">
        <h4>🔧 示例演示</h4>
        <p>${exampleData}</p>
      </div>

      <div class="code-exercise">
        <div class="code-prompt">
          <p><strong>代码示例：</strong>查看${currentState.currentContent.title}的实际应用</p>
        </div>

        <div class="desktop-code-editor">
          <pre style="background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace; line-height: 1.5;">
// ${currentState.currentContent.title} 示例代码
public class Example {
    public static void main(String[] args) {
        ${getExampleCode(currentState.currentContent.title)}
    }
}</pre>
        </div>
      </div>

      <div style="margin-top: 20px; background: #f8fff8; padding: 15px; border-radius: 8px; border-left: 4px solid var(--success-color);">
        <h4>💡 示例解析</h4>
        <p>通过这个示例，你可以看到${currentState.currentContent.title}在实际项目中的应用方式和效果。</p>
      </div>
    </div>
  `;
  }

  // 根据知识点生成示例代码
  function getExampleCode(title) {
    if (title.includes('IoC') || title.includes('依赖注入')) {
      return `// 使用Spring IoC容器\nApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");\nUserService userService = context.getBean(UserService.class);\nuserService.process();`;
    } else if (title.includes('多线程')) {
      return `// 创建并启动线程\nThread thread = new Thread(() -> {\n    System.out.println("线程执行中...");\n});\nthread.start();`;
    } else if (title.includes('集合')) {
      return `// 使用List集合\nList<String> list = new ArrayList<>();\nlist.add("元素1");\nlist.add("元素2");\nSystem.out.println("集合大小: " + list.size());`;
    } else if (title.includes('异常')) {
      return `// 异常处理示例\ntry {\n    int result = 10 / 0;\n} catch (ArithmeticException e) {\n    System.out.println("捕获异常: " + e.getMessage());\n}`;
    } else {
      return `// ${title} 的示例代码\nSystem.out.println("这是 ${title} 的示例实现");`;
    }
  }

  // 动态生成示例内容
  function generateDynamicExample(title) {
    if (title.includes('IoC') || title.includes('依赖注入')) {
      return '在实际项目中，IoC容器负责管理所有Bean的生命周期。我们不需要手动创建对象，而是通过配置或注解让容器自动注入依赖。这种模式大大降低了代码的耦合度，提高了可测试性。';
    } else if (title.includes('多线程')) {
      return '多线程编程可以显著提高程序性能。在实际应用中，我们可以使用线程池来管理线程，避免频繁创建和销毁线程的开销，同时确保系统资源的合理利用。';
    } else if (title.includes('集合')) {
      return 'Java集合框架提供了丰富的数据结构。在实际开发中，我们需要根据具体需求选择合适的集合类型，比如需要快速查找时使用HashMap，需要保持顺序时使用ArrayList。';
    }
    return `让我们通过实际示例来理解 ${title} 的具体应用。这个示例展示了该概念在实际项目中的典型用法。`;
  }
</script>
</body>
</html>